
# usr/bin/env python
# conding:utf-8
# 吕康宁，20201222
# car定位系统业务逻辑
# Create your views here.

from django.shortcuts import render
from .models import Device,Building,Scanner,Efence,Alarm,Myuser,Map_Data,Sys_Log,Command_Log,WIFI_LBS_ADDR,Car,Car_Apply,Person
from django.contrib.auth.models import User
from django.apps import apps
from django.views.decorators.csrf import csrf_exempt 
from django.http import HttpResponseRedirect,Http404,HttpResponse,FileResponse
from django.urls import reverse
from django.forms.models import model_to_dict
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.decorators import login_required

import redis
import numpy as np
import pandas as pd

from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.views import Response
from data_handle.change_lnglat import *
from data_handle.create_device_table import *
from data_handle.compute.report_compute import start_cacu

import datetime,json,random,time,uuid,requests,math
from math import pi,sin,cos

import base64,threading,sys,os,socket
# from .phone_app_api import *
from dwebsocket.decorators import accept_websocket,require_websocket
from sqlalchemy import desc
# ffmpeg的python封装，转换音视频，目前用途为转换小程序过来的aac为amr，下发给设备
import ffmpy3


Device_Base = automap_base()
Device_Base.prepare(engine, reflect=True)

pool_redis= redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)
mesg_redis=redis.Redis(connection_pool=pool_redis)


# 系统初次步数之后登陆，创建超级管理员账号
def init_superuser():

	admin_user=Myuser.objects.filter(username='admin').first()
	# Myuser.objects.filter(username='admin').update(kind='superuser')
	if admin_user==None:
		superuser={'username':'admin','visible_name':'超级管理员','phone':'0','leader':'0','subordinate':'0','kind':'superuser','character':{'kind':'superuser','user_icon':'/static/img/default.png','refresh_time':'60','alarm_audio':'on','alarm_show':'on','contact':'admin'},
				   'status':'on','remark':'0'}
		Myuser.objects.create(**(superuser))

init_superuser()

def base_respone():
	return {'code':1000,'data':'','error':'','msg':'操作成功'}
# 登录
@csrf_exempt
def logins(request):
	what=request.GET.get('what')
	if request.method=='GET':
		if what=='android_apk_down':
			file = open('car_app/static/carlink20210114.apk', 'rb')
			response = FileResponse(file)
			response['Content-Type'] = 'application/octet-stream' #设置头信息，告诉浏览器这是个文件
			response['Content-Disposition'] = 'attachment;filename=carlink20210114.apk'
			return response
		elif what=='demo':
			user=authenticate(username='demo',password='123456')
			if user is not None:
				if user.is_active:
					login(request,user)
					errors=0
					# 记录操作日志
					system_log(request,'登录')
					all_data=get_index_page_data(request)
					return render(request,'car_app/index.html',all_data)


	if request.method=='POST':
		
		name=request.POST.get('username')
		pwd=request.POST.get('password')
		request.data={'username':name,'password':pwd}
		# print(request.data)
		result=login_func(request)
		if result['code']==1000:
			user=authenticate(username=name,password=pwd)
			login(request,user)
		# print(result)

		return HttpResponse(json.dumps(result))

	return render(request,'car_app/login.html')
# ----首页start---- #
def get_index_page_data(request):
	username=str(request.user)
	user_self=Myuser.objects.filter(username=username).first()
	user_self=vars(user_self)
	user_self.pop('_state')
	character=user_self['character']
	character=eval(character)
	sub_user_result=get_subordinate_user(username,Myuser)
	sub_user=sub_user_result[0]
	user_tree=sub_user_result[1]
	all_user=sub_user.copy()
	all_user.append(username)
	device=get_device_detail(all_user)
	alarm_data=get_alarm_data(all_user)
	building=list(Building.objects.filter(owner__in=all_user).values())
	scanner=list(Scanner.objects.filter(owner__in=all_user).values())
	map_data=list(Map_Data.objects.filter(owner__in=all_user).values())
	sub_user_detail=list(Myuser.objects.filter(username__in=sub_user).values())
	dev_model=get_device_model()
	# 数据汇总
	all_data={'device':device,'alarm_data':alarm_data,'building':building,'scanner':scanner,'dev_model':dev_model,
			  'map_data':map_data,'sub_user_detail':sub_user_detail,'user_tree':user_tree,'user_self':user_self,'character':character}

	return all_data

# index页面

# 参数校验
def post_param_check(param_list,data,attach=None):
	error=[]
	result=data
	for x in param_list:
		param=data.get(x)
		if param==None or param==attach:
			error.append(x+'-为空')
	if len(error)!=0:
		error={'param_error':error}
		result=error

	return result

def handle_alarm(request,handle_data):

	res=base_respone()
	# 参数校验
	param_list=['alarm_name_list','alarm_handle_mark']
	handle_data=post_param_check(param_list,handle_data)
	if handle_data.get('param_error')!=None:
		res['error']=handle_data.get('param_error')
		res['code']=1234
		return res

	alarm_name=handle_data.get('alarm_name_list')
	handle=handle_data.get('alarm_handle_mark')

	res['error']=[]
	for x in alarm_name:
		if Alarm.objects.filter(name=x).first()!=None:
			Alarm.objects.filter(name=x).update(handle=handle)
		else:
			res['code']=1234
			res['error'].append(x)

	sys_re=''
	if res['code']==1000:
		sys_re='成功'
		alarm_data=get_alarm_data(subordinate_user)
		res['data']=alarm_data
	else:
		sys_re='失败'
		res['error']=str(res['error'])+'不存在'
		res['msg']='报警信息处理成功'

	system_log(request,'处理-'+str(alarm_name)+'-报警',sys_re)

	return res

def handle_password(request,handle_data):
	res=base_respone()
	old_password=handle_data['old_password']
	new_password=handle_data['new_password1']
	username=request.user
	user = authenticate(username=username, password=old_password)

	if user is not None:
		user.set_password(new_password)
		user.save()
		system_log(request,'修改密码')
		res['msg']='密码修改成功'
	else:
		system_log(request,'修改密码','失败')
		res['code']=1234
		res['error']='修改密码失败'

	return res

@login_required
@csrf_exempt
def index(request):
	res=base_respone()
	username=str(request.user)
	subordinate_user=get_subordinate_user(username,Myuser)[0]
	subordinate_user.append(str(request.user))
	what=request.GET.get('what')

	if request.method=='GET':
		if what=='get_alarm':
			alarm_data=get_alarm_data(subordinate_user)
			# 报警模拟数据
			if len(alarm_data)==0:
				dev=Device.objects.filter(owner__in=subordinate_user).first()
				if dev!=None:
					pt=simulate_point(dev.device_id)
					# ln=str({'satelite':[pt['lng'],pt['lat']]})
					ln={'wifi': "[{'ssid': 'a', 'mac': '78:f5:57:0a:ef:44', 'rssi': '61'}, {'ssid': 'a', 'mac': '78:f5:57:0a:ef:44', 'rssi': '61'}, {'ssid': 'a', 'mac': '78:58:60:99:ac:6c', 'rssi': '57'}]"}
					alarm_data=[{'name':'circleefence001',
								'device_id':dev.device_id,
								'location':str(ln),
								'content':'模拟数据',
								'kind':'circle',
								's_time':'0',
								'e_time':'0',
								'handle':'no',
								'remark':'0',
								'owner':'demo',
								'id':1}]
			res['data']=alarm_data
			return HttpResponse(json.dumps(res))

	if request.method=='POST':
		# 报警信息处理
		if what=='handle_alarm':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_alarm(request,handle_data)
			return HttpResponse(json.dumps(handle_result))

		# 修改密码
		elif what=='handle_password':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_password(request,handle_data)
			return HttpResponse(json.dumps(handle_result))

		elif what=='get_wifi_lbs_addr':
			handle_data=eval(request.POST.get('base_info'))
			track_type=handle_data.get('track_type')
			device_id=handle_data.get('device_id')
			track_data=handle_data.get('track_data')
			address_result=eval('get_'+track_type+'_address('+track_data+','+device_id+')')
			# print('address=====',address_result)
			address='0'
			if address_result!='':
				loca=address_result[2]
				if isinstance(loca,dict):
					loca=loca['desc']
				else:
					loca=eval(loca)
					loca=loca['desc']

				lnglat=wgs84_to_bd09(float(address_result[0]),float(address_result[1]))
				# if map_kind=='bd':
				# 	lnglat=wgs84_to_bd09(float(address_result[0]),float(address_result[1]))
				# elif map_kind=='gd':
				# 	lnglat=wgs84_to_gcj02(float(address_result[0]),float(address_result[1]))

				address={'lng':lnglat['lng'],'lat':lnglat['lat'],'location':loca}

			res['data']=address
			return HttpResponse(json.dumps(res))

	all_data=get_index_page_data(request)

	return render(request,'car_app/index.html',all_data)

@login_required
@csrf_exempt
def normal_user_index(request):
	res=base_respone()
	username=str(request.user)
	subordinate_user=get_subordinate_user(username,Myuser)[0]
	subordinate_user.append(str(request.user))
	what=request.GET.get('what')
	user_data=Myuser.objects.filter(username=username).first()
	character=eval(user_data.character)
	dev_ids=character.get('device',[])
	if request.method=='GET':
		if what=='get_alarm':
			alarm_data=list(Alarm.objects.filter(device_id__in=dev_ids).filter(handle='no').values())
			# 报警模拟数据
			if len(alarm_data)==0:
				dev=Device.objects.filter(owner__in=subordinate_user).first()
				pt=simulate_point(dev.device_id)
				# ln=str({'satelite':[pt['lng'],pt['lat']]})
				ln={'wifi': "[{'ssid': 'a', 'mac': '78:f5:57:0a:ef:44', 'rssi': '61'}, {'ssid': 'a', 'mac': '78:f5:57:0a:ef:44', 'rssi': '61'}, {'ssid': 'a', 'mac': '78:58:60:99:ac:6c', 'rssi': '57'}]"}
				alarm_data=[{'name':'circleefence001',
							'device_id':dev.device_id,
							'location':str(ln),
							'content':'模拟数据',
							'kind':'circle',
							's_time':'0',
							'e_time':'0',
							'handle':'no',
							'remark':'0',
							'owner':'demo',
							'id':1}]
			res['data']=alarm_data
			return HttpResponse(json.dumps(res))
		elif what=='get_device':
			device=Device.objects.filter(device_id__in=dev_ids).values()
			device=list(device)
			device=pd.DataFrame(device)
			if device.empty!=True:
				device=handle_dynamic_data(device,'bd')
			else:
				device=[]
			res['data']=device
			return HttpResponse(json.dumps(res))


	if request.method=='POST':
		# 报警信息处理
		if what=='handle_alarm':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_alarm(request,handle_data)
			return HttpResponse(json.dumps(handle_result))

		# 修改密码
		elif what=='handle_password':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_password(request,handle_data)
			return HttpResponse(json.dumps(handle_result))

		elif what=='get_wifi_lbs_addr':
			handle_data=eval(request.POST.get('base_info'))
			track_type=handle_data.get('track_type')
			device_id=handle_data.get('device_id')
			track_data=handle_data.get('track_data')
			address_result=eval('get_'+track_type+'_address('+track_data+','+device_id+')')
			# print('address=====',address_result)
			address='0'
			if address_result!='':
				loca=address_result[2]
				if isinstance(loca,dict):
					loca=loca['desc']
				else:
					loca=eval(loca)
					loca=loca['desc']

				lnglat=wgs84_to_bd09(float(address_result[0]),float(address_result[1]))
				# if map_kind=='bd':
				# 	lnglat=wgs84_to_bd09(float(address_result[0]),float(address_result[1]))
				# elif map_kind=='gd':
				# 	lnglat=wgs84_to_gcj02(float(address_result[0]),float(address_result[1]))

				address={'lng':lnglat['lng'],'lat':lnglat['lat'],'location':loca}

			res['data']=address
			return HttpResponse(json.dumps(res))
		elif what=='add_permi_dev':
			handle_data=eval(request.POST.get('base_info'))
			device_id=handle_data['device_id']
			dev=Device.objects.filter(device_id=device_id).first()
			if dev==None:
				res['code']=1234
				res['error']='设备编号不存在'
			else:
				auth_id=dev.auth_id
				if handle_data['auth_id']!=auth_id:
					res['code']=1234
					res['error']='授权码不正确'
				else:
					dev_ids.append(device_id)
					character['device_id']=dev_ids
					Myuser.objects.filter(username=username).update(character=str(character))
					device=Device.objects.filter(device_id__in=dev_ids).values()
					device=list(device)
					device=pd.DataFrame(device)
					device=handle_dynamic_data(device,'bd')
					res['data']=device

			return HttpResponse(json.dumps(res))

	all_data={}
	dev_model=get_device_model()
	alarm_data=list(Alarm.objects.filter(device_id__in=dev_ids).filter(handle='no').values())
	user_data=vars(user_data)
	user_data.pop('_state')

	device=Device.objects.filter(device_id__in=dev_ids).values()
	device=list(device)
	device=pd.DataFrame(device)
	if device.empty!=True:
		device=handle_dynamic_data(device,'bd')
	else:
		device=[]

	all_data={'device':device,'alarm_data':alarm_data,'building':[],'scanner':[],'dev_model':dev_model,
			  'map_data':[],'sub_user_detail':[],'user_tree':[],'user_self':user_data,'character':character}

	return render(request,'car_app/normal_user_index.html',all_data)

# 实时监控页面渲染
# 参数设置处理
def handle_param_set(data,request,subordinate_user):
	res=base_respone()
	device_id=data.pop('device_id')
	detail=Device.objects.filter(device_id=device_id).first()
	if detail!=None:
		new_set=''
		param_set=detail.param_set
		if param_set=='0' or param_set=='':
			new_set=str(data)
		else:
			param_set=eval(param_set)
			param_set.update(data)
			new_set=str(param_set)

		Device.objects.filter(device_id=device_id).update(param_set=new_set)
		system_log(request,device_id+'-参数设置-'+str(data))
		
	else:
		system_log(request,device_id+'-参数设置-'+str(data),'失败')
		res['code']=1234
		res['error']='设置失败（设备为None）'

	return res

@login_required
@csrf_exempt
def dynamic(request):

	username=str(request.user)
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(str(request.user))
	what=request.GET.get('what')
	if request.method=='GET':
		if what=='get_init_data':
			res=base_respone()
			user_character=eval(Myuser.objects.get(username=request.user).character)
			device=get_device_detail(subordinate_user)
			res['data']=device
			return HttpResponse(json.dumps(res))
	if request.method=='POST':
		#报警参数设置数据处理（系统参数设定，绑定设备，不改变硬件本身的参数）
		if what=='alarm_set':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_param_set(handle_data,request,subordinate_user)
			res_data=get_device_detail(subordinate_user)
			handle_result['data']=res_data
			return HttpResponse(json.dumps(handle_result))

		#设备硬件参数设置（给设备发指令，改变硬件本身的参数）
		elif what=='device_set':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_command(handle_data,username,'device_set')

			return HttpResponse(json.dumps(handle_result))

		#给设备下发命令
		elif what=='order_dowm':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_command(handle_data,username,'order')
	
			return HttpResponse(json.dumps(handle_result))

		#追踪
		elif what=='tracking':
			handle_data=eval(request.POST.get('base_info'))
			handle_result=handle_tracking(handle_data)
			# 模拟数据	
			if handle_result['error']=='设备尚未启用':
				handle_result['code']=1000
				handle_result['data']=simulate_point(handle_data['device_id'])

			return HttpResponse(json.dumps(handle_result))


	# return render(request,'car_app/dynamic.html')
def simulate_point(device_id,min_lng=100.394801,min_lat=24.913303,max_lng=118.394801,max_lat=39.913303,min_num=-0.0001,max_num=0.0009):

	simu=mesg_redis.get('simulate_point'+device_id)
	if simu==None:
		simu={}
		simu['lng']=random.uniform(min_lng,max_lng)
		simu['lat']=random.uniform(min_lat,max_lat)
		simu['id']=1
	else:
		simu=eval(simu)
		simu['lng']+=random.uniform(min_num,max_num)
		simu['lat']+=random.uniform(min_num,max_num)
		simu['id']+=1
	dirct=random.randint(1,360)
	default={'on_off_line':'online','lng': '0', 'lat': '0', 'lbs': '0', 'wifi': '0', 'rssi': '0', 'heart_rate': '0', 'blood_pres': '0', 'step_count': '0', 'obd': '0', 'track_type': '0', 'speed': '0', 'dirct': dirct, 'status': '0', 'battery': '0', 'sos_alarm': '0', 'dev_upload': '0', 'serv_receive': '0', 'hard_verson': '0', 'mileage': '0', 'oil_use': '0', 'efence_alarm': '0', 'speed_alarm': '0', 'stop_time': '0', 'location': '0', 'othermesg': '模拟数据', 'scanner': '0', 'heart_alarm': '0', 'blood_alarm': '0', 'receive_port': '0'}
	default['serv_receive']=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	default.update(simu)
	mesg_redis.set('simulate_point'+device_id,str(simu),ex=600)

	return default

	

def handle_tracking(data):
	res=base_respone()
	map_kind=data['map_kind']
	device_id=str(data['device_id'])
	
	dev_table=Device_Base.classes[device_id]
	new_dynamic=session.query(dev_table).order_by(dev_table.id.desc()).first()


	if new_dynamic==None:
		res['code']=1234
		res['error']='设备尚未启用'
		return res
	mark=str(new_dynamic.id)
	old_data=mesg_redis.get('tracking'+device_id)
	if old_data==mark:
		res['code']=1234
		res['error']='无新消息'
	else:
		dev=Device.objects.filter(device_id=device_id).first()
		dev=vars(dev)
		dev.pop('_state')
		
		new_dynamic=vars(new_dynamic)
		new_dynamic['lng']=float(new_dynamic['lng'])
		new_dynamic['lat']=float(new_dynamic['lat'])
		new_dynamic.pop('_sa_instance_state')
		dev['dynamic']=str(new_dynamic)
		dev=pd.DataFrame([dev]) #转换之后的数据不正常，原因不明。
		res['data']=handle_dynamic_data(dev,map_kind)[0]
		res['msg']='有新消息'


	mesg_redis.set('tracking'+device_id,mark,ex=600)

	return res

# 获取设备型号
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def get_device_model(file_path=''):
	# file_path='F:\\car\\data_handle\\device_model.xlsx'
	sys_platform=sys.platform[0:3]
	if file_path=='':
		if sys_platform=='win':
			file_path=BASE_DIR+'\\data_handle\\device_model.xls'
		else:
			file_path=BASE_DIR+'/data_handle/device_model.xls'
	# print(sys_platform,file_path)
	detail=pd.read_excel(file_path,sheet_name = None)
	for x in detail:
		detail[x]=detail[x].fillna('无')
	base_data=detail['基本数据'].to_json(orient="records",force_ascii=False)
	base_data=eval(base_data)
	datakind=detail['数据种类'].to_json(orient="records",force_ascii=False)
	datakind=eval(datakind)
	command=detail['命令下发'].to_json(orient="records",force_ascii=False)
	command=eval(command)
	param_set=detail['参数设置'].to_json(orient="records",force_ascii=False)
	param_set=eval(param_set)
	alarm_set=detail['报警类型'].to_json(orient="records",force_ascii=False)
	alarm_set=eval(alarm_set)
	for x in base_data:
		# print(x)
		for y in datakind:
			if x['unique_id']==y['unique_id']:
				x['datakind']=y
				# x['datakind'].pop('unique_id')
		for z in command:
			if x['unique_id']==z['unique_id']:
				x['command']=z
		for n in param_set:
			if x['unique_id']==n['unique_id']:
				x['param_set']=n
		for l in alarm_set:
			if x['unique_id']==l['unique_id']:
				x['alarm_set']=l

	return base_data
	
@login_required
@csrf_exempt
def device(request):
	res = base_respone()
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(str(request.user))
	what=request.GET.get('what')
	if request.method=='GET':
		if what=='get_init_data':
			dev_data=list(Device.objects.all().filter(owner__in=subordinate_user).values())
			res['data']=dev_data
			return HttpResponse(json.dumps(res))

	if request.method=='POST':
		handle_data=eval(request.POST.get('base_info'))
		save_data=handle_data.copy()
		# print(handle_data)

		# 添加单台设备
		if what=='add':
			save_data=package_device_data(save_data,request,subordinate_user)
		# 设备通过文件批量导入设备
		elif what=='add_from_file':

			result=[]
			for device_data in save_data:
				new_data=package_device_data(device_data,request,subordinate_user)
				result.append(new_data)
			save_data=result
				
		# 对设备进行转移分配处理，需要进行单独的解绑处理，把绑定的用户信息和围栏信息清空
		
		elif what in ['change_owner','del']:
			device_list=[]
			if what=='change_owner':
				device_list=handle_data['device_id']
			elif what=='del':
				device_list.append(handle_data['device_id'])
				# 深度删除设备，才把原始数据的存储表格删除
				if handle_data.get('deep_clear')=='yes':
					del_res=drop_table(handle_data['device_id'])
				# print(del_res)
			for device_id in device_list:
				# 历遍device绑定的围栏，把相应围栏里面相应的device_id去掉
				dev_detail=Device.objects.filter(device_id=device_id).first()
				if dev_detail!=None:
					efe_of_dev=dev_detail.efence
					if efe_of_dev!='0':
						if isinstance(eval(efe_of_dev),dict)==True:
							for efence_name in eval(efe_of_dev):
								efence_device_list=Efence.objects.filter(name=efence_name).first().device_id
								efence_device_list=eval(efence_device_list)
								if device_id in efence_device_list:
									efence_device_list.remove(device_id)
								Efence.objects.filter(name=efence_name).update(device_id=str(efence_device_list))

					# 把device里的efence围栏信息，user_detail用户信息的信清空，用户归属更改为目标用户
					Device.objects.filter(device_id=device_id).update(efence='0')
					bind_name=eval(dev_detail.user_detail)['name']
					# device绑定的使用者，把相应的device_id重置为空
					refresh_table_field(Car,'name',bind_name,'device_id','')
					# 设备的user_detail字段清空相应内容
					refresh_table_field(Device,'device_id',device_id,'user_detail',{'kind':'','name':''},'dict')

		hanlde_result=database_handle('设备',what,Device,'device_id',save_data,subordinate_user,str(request.user))
		
		return HttpResponse(json.dumps(hanlde_result))


	return render(request,'car_app/device.html')


def package_device_data(org_data,request,subordinate_user):

	org_data['auth_id']=str(random.randint(1000,9999))
	user_name=org_data.get('user_name','')
	if user_name=='':
		org_data['user_name']=org_data['device_id']
	# org_data['dynamic']='0'
	# org_data['user_detail']={'user_name':org_data['user_name'],'department':'0','c_model':'0','insurance':'0','maitain':'0','driver':'0','icon_show':'0'}
	# org_data['param_set']={'send_rate':'30','speed_limit':'180','efence':'0','stop_rate':'0'}
	# 对设备的dynamic动态信息做初始化设置，对应的后台应该判断基本参数的动态信息是否有具体内容，如果为零，则不做计算判断处理。
	dynamic_field={'lng':'0','lat':'0','lbs':'0','wifi':'0',
						'rssi':'0','heart_rate':'0','blood_pres':'0','step_count':'0',
						'obd':'0','track_type':'0','speed':'0','dirct':'0','status':'0',
						'battery':'0','sos_alarm':'0','dev_upload':'0','serv_receive':'0','hard_verson':'0',
						'mileage':'0','oil_use':'0','efence_alarm':'0','speed_alarm':'0','stop_time':'0',
						'location':'0','othermesg':'0','scanner':'0','heart_alarm':'0','blood_alarm':'0',
						'receive_port':'0'}
	org_data['dynamic']=dynamic_field
	if org_data.get('owner')==None:
		org_data['owner']=str(request.user)
	else:
		if org_data['owner'] not in subordinate_user:
			org_data['owner']=str(request.user)
	# 创建一条设备信息
	# 创建一张以设备tracker+ID的独立数据表，用来存储该设备的所有数据历史数据
	# print(org_data['device_id'],type(org_data['device_id']))
	creat_device_table(org_data['device_id'])
	return org_data

# ----设备管理end---- #




#用户管理页面
@csrf_exempt
def user_manage(request):
	res = base_respone()
	username=str(request.user)
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(username)
	what=request.GET.get('what')

	if request.method=='GET':
		if what=='get_init_data':
			user_list=subordinate_user.copy()
			user_list.remove(username)
			data=Myuser.objects.filter(username__in=user_list).values()
			res['data']=list(data)
			return HttpResponse(json.dumps(res))

	if request.method=='POST':
		handle_data=eval(request.POST.get('base_info'))
		if what=='add':
			# 增加数据
			handle_data['leader']=str(request.user)
			handle_result=database_handle('子用户',what,Myuser,'username',handle_data,subordinate_user,username)
			# 在django自带的user里面创建用户，用户登录和登出的操作
			User.objects.create_user(username=handle_data['username'],password='123456')
			# 把新建的子账号添加到子用户列表
			old_subordinate=Myuser.objects.filter(username=request.user).first().subordinate
			if old_subordinate=='0':
				Myuser.objects.filter(username=request.user).update(subordinate=handle_data['username'])
			else:
				Myuser.objects.filter(username=request.user).update(subordinate=old_subordinate+','+handle_data['username'])
			subordinate_user.append(handle_data['username'])
			user_data=list(Myuser.objects.filter(username__in=subordinate_user).values())
			handle_result['data']=user_data
			return HttpResponse(json.dumps(handle_result))

		# 修改数据
		elif what=='edit':
			handle_result=database_handle('子用户',what,Myuser,'username',handle_data,subordinate_user,username)
			return HttpResponse(json.dumps(handle_result))
		# 重置密码
		elif what=='reset_pwd':
			
			user = User.objects.get(username=handle_data['username'])
			if user is not None:
				user.set_password('123456')
				user.save()
				res['data']='重置密码成功,新密码：123456'
			else:
				res['code']=1234
				res['data']='重置密码失败'

			system_log(request,'重置密码-'+handle_data['username'],res['data'])

			return HttpResponse(json.dumps(res))


		#用户启用停用处理
		elif what=='user_status':
			handle_data=eval(request.POST.get('base_info'))
			title=''
			if handle_data['status']=='on':
				title='停用账号-'+handle_data['username']
				User.objects.filter(username=handle_data['username']).update(is_active=False)
				Myuser.objects.filter(username=handle_data['username']).update(status='off')
			else:
				title='启用账号-'+handle_data['username']
				User.objects.filter(username=handle_data['username']).update(is_active=True)
				Myuser.objects.filter(username=handle_data['username']).update(status='on')

			user_data=list(Myuser.objects.all().filter(username__in=subordinate_user).values())
			res['data']=user_data
			system_log(request,title)
			return HttpResponse(json.dumps(res))

	return render(request,'car_app/user_manage.html')

@csrf_exempt
def car_board(request):
	res = base_respone()
	current_user=str(request.user)
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	sub_user_id=subordinate_user.copy()
	subordinate_user.append(current_user)
	what=request.GET.get('what')

	if request.method=='GET':
		if what=='get_init_data':

			return_data={}
			car_data=list(Car.objects.filter(owner__in=subordinate_user).values())
			apply_data=list(Car_Apply.objects.filter(owner__in=sub_user_id).values())
			sub_user=list(Myuser.objects.filter(username__in=sub_user_id).values())
			
			return_data['car_data']=car_data
			return_data['apply_data']=apply_data
			return_data['sub_user']=sub_user
			res['data']=return_data

		return HttpResponse(json.dumps(res))


@csrf_exempt
def car_manage(request):
	res = base_respone()
	current_user=str(request.user)
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(current_user)
	what=request.GET.get('what')

	if request.method=='GET':
		if what=='get_init_data':

			return_data={}
			car_data=list(Car.objects.filter(owner__in=subordinate_user).values())
			dev_data=list(Device.objects.filter(owner__in=subordinate_user).values())
			dev_data=pd.DataFrame(dev_data)
			dev_data.loc[:,'in_use']=dev_data['user_detail'].map(lambda x:'no' if eval(x).get('name')=='' or None  else 'yes')
			dev_data=dev_data.loc[dev_data['in_use']=='no']
			dev_data=json.loads(dev_data.to_json(orient="records",force_ascii=False))
			return_data['car_data']=car_data
			return_data['dev_data']=dev_data
			res['data']=return_data

		return HttpResponse(json.dumps(res))


	if request.method=='POST':

		handle_data=eval(request.POST.get('base_info'))

		if what!='add_from_file':
			detail=handle_data.get('detail')
			if detail!=None:
				if what=='del':
					detail=eval(handle_data['detail'])
					picture=detail['picture']
					if picture !='0' and picture!='':
						remove_picture('car',handle_data['name'])
				else:
					detail=handle_data['detail']
					picture=detail['picture']
					if picture!='0' and len(picture)>200:
						picture_path=store_picture(picture,'car',handle_data['name'])
						detail['picture']=picture_path

					handle_data['detail']=str(detail)

		if what=='add':
			handle_data['owner']=str(request.user)

		bind_data=handle_data.copy()

		# 与标签绑定解绑操作，先进行解绑和绑定操作，再对rcw进行增删改
		handle_bind_func(Device,Car,bind_data,what)
		# 增删改操作
		hanlde_result=database_handle('车辆',what,Car,'name',handle_data,subordinate_user,current_user)

		return HttpResponse(json.dumps(hanlde_result))

	return render(request,'car_app/car_manage.html')


# 根据字段更新数据功能函数
def refresh_table_field(table,key_field,key_value,refresh_field,refresh_value,kind='string'):
	detail=table.objects.filter(**{key_field:key_value}).first()
	if detail!=None:
		detail=vars(detail)
		detail.pop('_state')
		old_data=detail[refresh_field]			
		if kind=='dict':
			old_data=eval(old_data)
			if isinstance(old_data,dict)==True and isinstance(refresh_value,dict)==True:
				old_data.update(refresh_value)
		elif kind=='list_add':
			old_data=eval(old_data)
			if isinstance(old_data,list)==True:
				old_data.append(refresh_value)
		elif kind=='list_remove':
			old_data=eval(old_data)
			if isinstance(old_data,list)==True:
				old_data.remove(refresh_value)
		else:
			old_data=refresh_value
		# print('old_data222==>',old_data)
		table.objects.filter(**{key_field:key_value}).update(**{refresh_field:str(old_data)})
# 设备关联的人车物的绑定与解绑操作
def handle_bind_func(dev_table,rcw_table,handle_data,what):

	# table_chose={Person:'Person',Asset:'Asset',Car:'Car'}
	table_chose={Person:'Person',Car:'Car'}
	rcw_name=''
	new_bind_dev=''
	if what!='add_from_file':
		rcw_name=handle_data.get('name')
		new_bind_dev=handle_data.get('device_id')

	# 获取已经绑定的device_id
	old_bind_dev=rcw_table.objects.filter(name=rcw_name).first()
	if old_bind_dev!=None:
		old_bind_dev=old_bind_dev.device_id
	else:
		old_bind_dev=''

	# 绑定到device的user_userdetail字段的内容
	user_detail={'kind':table_chose[rcw_table],'name':rcw_name}
	cancle={'kind':'','name':''}
	if what=='add':
		refresh_table_field(dev_table,'device_id',new_bind_dev,'user_detail',user_detail,kind='dict')

	# 设备通过文件批量新增
	elif what=='add_from_file':
		for add_data in handle_data:
			name=add_data.get('name')
			bind_dev=add_data.get('device_id')
			user_detail={'kind':table_chose[rcw_table],'name':name}
			refresh_table_field(dev_table,'device_id',bind_dev,'user_detail',user_detail,kind='dict')
			
	# 编辑修改
	elif what=='edit':
		if new_bind_dev!=old_bind_dev:
			# 解绑旧设备
			refresh_table_field(dev_table,'device_id',old_bind_dev,'user_detail',cancle,kind='dict')
			# 绑定新设备
			print('user_detail==>',user_detail)
			refresh_table_field(dev_table,'device_id',new_bind_dev,'user_detail',user_detail,kind='dict')

	# 删除
	elif what=='del':
		refresh_table_field(dev_table,'device_id',old_bind_dev,'user_detail',cancle,kind='dict')

	elif what=='change_owner':
		# print('rcw_name====>',rcw_name)
		for n in rcw_name:
			# 解绑旧设备
			if rcw_table.objects.filter(name=n).first()!=None:
				bind_dev_id=rcw_table.objects.filter(name=n).first().device_id
				# print('bind_dev_id===>',bind_dev_id)
				if dev_table.objects.filter(device_id=bind_dev_id).first()!=None:
					# 设备上的用户数据清空
					refresh_table_field(dev_table,'device_id',bind_dev_id,'user_detail',cancle,kind='dict')
					# 用户上的绑定设备信息清空
					rcw_table.objects.filter(name=n).update(device_id='')



@csrf_exempt
def car_apply(request):

	current_user=str(request.user)
	what=request.GET.get('what')
	handle_data=''

	if request.method=='POST':
		handle_data=eval(request.POST.get('base_info'))

	handle_result=handle_car_apply(what,current_user,handle_data)
	return HttpResponse(json.dumps(handle_result))

	# return render(request,'car_app/car_apply.html')

def handle_car_apply(what,current_user,handle_data=''):
	res = base_respone()
	if what=='get_init_data':
		apply_data=list(Car_Apply.objects.filter(owner=current_user).values())
		res['data']=apply_data
	else:
		if what=='add':
			handle_data['owner']=current_user
			handle_data['status']='已提交，待审批'
		else:
			key_param=handle_data.get('id')
			if key_param==None:
				res['code']=1234
				res['error']='申请id字段缺失'
				return res
			else:
				d=Car_Apply.objects.filter(id=key_param).first()
				if d==None:	
					res['code']=1234
					res['error']='申请id参数错误，查找不到申请数据'
					return res
				else:
					print(d.owner,current_user)
					if d.owner!=current_user:
						res['code']=1234
						res['error']='申请id不属于当前用户，无法操作'
						return res

		handle_result=database_handle('用车申请',what,Car_Apply,'id',handle_data,[current_user],current_user)
		if handle_result['code']==1000:
			apply_data=list(Car_Apply.objects.filter(owner=current_user).values())
			handle_result['data']=apply_data

		res=handle_result

	return res

@csrf_exempt
def car_apply_approve(request):
	current_user=str(request.user)
	what=request.GET.get('what')
	handle_data=''
	if request.method=='POST':
		handle_data=eval(request.POST.get('base_info'))

	handle_result=handle_car_apporve(what,current_user,handle_data)

	return HttpResponse(json.dumps(handle_result))

	# return render(request,'car_app/car_apply_approve.html')

# 用车申请审批
def handle_car_apporve(what,current_user,handle_data=''):
	res = base_respone()
	subordinate_user=get_subordinate_user(current_user,Myuser)[0]
	subordinate_user.append(current_user)
	current_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	# 校验参数
	if handle_data!='' and handle_data!=None:
		# 校验ID
		key_param=handle_data.get('id')
		if key_param==None:
			res['code']=1234
			res['error']='申请id字段缺失'
			return res
		else:
			d=Car_Apply.objects.filter(id=key_param).first()
			if d==None:	
				res['code']=1234
				res['error']='申请id参数错误，查找不到申请数据'
				return res
			else:
				if d.owner==current_user:
					res['code']=1234
					res['error']='申请id属于当前用户，无法审批自己的申请'
					return res

			if d.start!= handle_data['start'] or d.end!=handle_data['end']:
				res['code']=1234
				res['error']='申请id与申请参数不匹配'
				return res

	def get_return_data():
		return_data={}
		sub_user_id=subordinate_user.copy()
		sub_user_id.remove(current_user)
		apply_data=list(Car_Apply.objects.filter(owner__in=sub_user_id).values())
		car_data=list(Car.objects.filter(status='0').values())
		return_data['apply_data']=apply_data
		return_data['car_data']=car_data
		sub_user=list(Myuser.objects.filter(username__in=subordinate_user).values())
		return_data['sub_user']=sub_user
		res['data']=return_data
		return res

	if what=='get_init_data':
		result=get_return_data()
		return result

	
	elif what=='pass':
		car = handle_data.get('car')
		car_detail=Car.objects.filter(name=car).first()
		if car_detail==None:
			res['code']=1234
			res['error']='车辆数据错误'
		else:
			if car_detail.status!='0':
				res['code']=1234
				res['error']='车辆已经在使用中'
			else:			
				handle_data['status']='审批通过'
				get_key_code=str(random.randint(1000,9999))
				# 车钥匙状态，un_get:未取,get：已取,back：已归还
				param_set={'get_key_code':get_key_code,'key_status':'un_get','approver':current_user,'approve_time':current_time}
				handle_data['param_set']=str(param_set)

				Car_Apply.objects.filter(id=handle_data['id']).update(**handle_data)
				# 被预定的车辆，状态字段绑定申请信息
				car_status={'apply_id':handle_data['id']}
				Car.objects.filter(name=car).update(status=str(car_status))

	elif what=='reject':
		handle_data['status']='审批未通过'
		param_set={'reject':handle_data['param_set'],'approver':current_user,'approve_time':current_time}
		handle_data['param_set']=str(param_set)
		Car_Apply.objects.filter(id=handle_data['id']).update(**handle_data)
	elif what=='get_key':
		# 车钥匙状态，un_get:未取,get：已取,back：已归还
		apply_data=Car_Apply.objects.filter(id=handle_data['id']).first()
		param_set=eval(apply_data.param_set)
		get_key_code=param_set['get_key_code']
		if handle_data['get_key_code']!=get_key_code:
			res['code']=1234
			res['error']='验证码错误'
		else:
			# handle_data.pop('get_key_code')
			param_set['get_key_time']=current_time
			param_set['key_status']='get'
			param_set['get_key_handler']=current_user
			apply_data=vars(apply_data)
			apply_data.pop('_state')
			apply_data['param_set']=str(param_set)
			Car_Apply.objects.filter(id=handle_data['id']).update(**apply_data)
	elif what=='back_key':

		# 车钥匙状态，un_get:未取,get：已取,back：已归还
		apply_data=Car_Apply.objects.filter(id=handle_data['id']).first()
		param_set=eval(apply_data.param_set)
		param_set['back_key_time']=current_time
		param_set['key_status']='back'
		param_set['back_key_handler']=current_user

		apply_data=vars(apply_data)
		apply_data.pop('_state')
		apply_data['param_set']=str(param_set)
		apply_data['status']='申请完结'
		Car_Apply.objects.filter(id=handle_data['id']).update(**apply_data)
		# 归还的车辆，状态字段归零
		Car.objects.filter(name=apply_data['car']).update(status='0')

	if res['code']==1000:
		result=get_return_data()
		res=result

	return res

@csrf_exempt
def person_manage(request):
	res = base_respone()
	current_user=str(request.user)
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(current_user)
	what=request.GET.get('what')

	if request.method=='GET':
		if what=='get_init_data':

			return_data={}
			person_data=list(Person.objects.filter(owner__in=subordinate_user).values())
			dev_data=list(Device.objects.filter(owner__in=subordinate_user).values())
			dev_data=pd.DataFrame(dev_data)
			dev_data.loc[:,'in_use']=dev_data['user_detail'].map(lambda x:'no' if eval(x).get('name')=='' or None  else 'yes')
			dev_data=dev_data.loc[dev_data['in_use']=='no']
			dev_data=json.loads(dev_data.to_json(orient="records",force_ascii=False))
			return_data['person_data']=person_data
			return_data['dev_data']=dev_data
			res['data']=return_data

		return HttpResponse(json.dumps(res))


	if request.method=='POST':

		handle_data=eval(request.POST.get('base_info'))

		if what!='add_from_file':
			detail=handle_data.get('detail')
			if detail!=None:
				if what=='del':
					detail=eval(handle_data['detail'])
					picture=detail['picture']
					if picture !='0' and picture!='':
						remove_picture('person',handle_data['name'])
				else:
					detail=handle_data['detail']
					picture=detail['picture']
					if picture!='0' and len(picture)>200:
						picture_path=store_picture(picture,'person',handle_data['name'])
						detail['picture']=picture_path

					handle_data['detail']=str(detail)

		if what=='add':
			handle_data['owner']=str(request.user)

		bind_data=handle_data.copy()

		# 与标签绑定解绑操作，先进行解绑和绑定操作，再对rcw进行增删改
		handle_bind_func(Device,Person,bind_data,what)
		# 增删改操作
		hanlde_result=database_handle('人员',what,Person,'name',handle_data,subordinate_user,current_user)

		return HttpResponse(json.dumps(hanlde_result))

	return render(request,'car_app/person_manage.html')


# print(Car_Apply.objects.all().values())
# 操作日志查询
@csrf_exempt
def sys_log_web(request):
	res=base_respone()
	if request.GET.get('what')=='get_init_data':
		subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
		subordinate_user.append(str(request.user))
		sys_log_data=list(Sys_Log.objects.all().filter(owner__in=subordinate_user).values())
		res['data']=sys_log_data
		return HttpResponse(json.dumps(res))

	if request.method=='POST':
		if request.GET.get('what')=='query_log':
			query_param=eval(request.POST.get('base_info'))
			user_list=query_param['hard_id']
			s_time=query_param['s_time']
			e_time=query_param['e_time']
			
			log_detail=Sys_Log.objects.filter(owner__in=user_list).filter(date_added__lt=e_time).filter(date_added__gt=s_time).values()
			
			res['data']=list(log_detail)

			return HttpResponse(json.dumps(res))
	

#轨迹回放
@csrf_exempt
def trail(request):

	res=base_respone()

	if request.method=='POST' and request.GET.get('what')=='get_trail':

		trail_param=request.POST.get('base_info')
		trail_param=eval(trail_param)
		
		trail_detail_data=handle_trail(trail_param)
		device_id=trail_param['device_id']

		if len(trail_detail_data)==0:
			for x in range(40):
				trail_detail_data.append(simulate_point(device_id))

		res['data']=trail_detail_data
		res['msg']='轨迹数据加载完毕'

		return HttpResponse(json.dumps(res))

	device_check=''
	if request.GET.get('params'):
		params=request.GET.get('params')
		for x in devices_all:
			if x['device_id']==params:
				device_check=x
	else:
		device_check='0'

	return render(request,'car_app/trail.html')

def handle_trail(trail_param):
	result=base_respone()
	# 校验参数
	param_list=['device_id','s_time','e_time','map_kind','trail_filter']
	trail_param=post_param_check(param_list,trail_param)
	if trail_param.get('param_error')!=None:
		result['msg']='参数缺失='+str(trail_param.get('param_error'))
		result['data']=[]
		return result

	device_id=trail_param['device_id']
	s_time=trail_param['s_time']
	e_time=trail_param['e_time']
	track_kind=trail_param['trail_filter']
	map_kind=trail_param['map_kind']

	refresh_session(device_id)

	sql_content = 'select * from "'+device_id+'" where dev_upload between \''+s_time+'\' and \''+e_time+'\''
	dev_data = pd.read_sql_query(sql_content,engine)
	# print('trail_org_data==>',dev_data)

	def get_address_from_wifilbs(trail,track_kind):

		res={'lng':'0','lat':'0'}

		if trail['lng']!='0' and trail['lat']!='0' and 'satelite' in track_kind:
			res={'lng':trail['lng'],'lat':trail['lat']}

		elif trail['wifi']!='0' and 'wifi' in track_kind:
			result=get_wifi_address(trail['wifi'],trail['device_id'])
			if result[0]!='0' and result[1]!='0':
				res={'lng':result[0],'lat':result[1]}


		elif trail['lbs']!='0' and 'lbs' in track_kind:
			result=get_lbs_address(trail['lbs'],trail['device_id'])
			if result[0]!='0' and result[1]!='0':
				res={'lng':result[0],'lat':result[1]}


		return res

	# print(dev_data.shape[0])
	if dev_data.shape[0]>1:
		# 排序和重置index索引 2020.09.04吕康宁
		dev_data=dev_data.sort_values('dev_upload')
		dev_data=dev_data.reset_index(drop=True)
		dev_data.loc[:,'trail']=dev_data.apply(lambda x:get_address_from_wifilbs(x,track_kind),axis=1)
		dev_data['lng']=dev_data['trail'].map(lambda x:x['lng'])
		dev_data['lat']=dev_data['trail'].map(lambda x:x['lat'])
		dev_data=dev_data.loc[dev_data['lng']!='0']
		dev_data=dev_data.loc[dev_data['lat']!='0']
		
	if dev_data.shape[0]>1:
		dev_data['lng'] = pd.to_numeric(dev_data['lng'])
		dev_data['lat'] = pd.to_numeric(dev_data['lat'])
		# 坐标系转换bd:百度,gd:高德
		if map_kind=='bd':
			dev_data.loc[:,'change_lnglat']=dev_data.apply(lambda x:wgs84_to_bd09(x['lng'],x['lat']) if x['lng']!='0' else '0',axis=1)
		elif map_kind=='gd':
			dev_data.loc[:,'change_lnglat']=dev_data.apply(lambda x:wgs84_to_gcj02(x['lng'],x['lat']) if x['lng']!='0' else '0',axis=1)
		dev_data['lng']=dev_data.apply(lambda x:x['change_lnglat']['lng'] if x['change_lnglat']!='0' else x['lng'],axis=1)
		dev_data['lat']=dev_data.apply(lambda x:x['change_lnglat']['lat'] if x['change_lnglat']!='0' else x['lat'],axis=1)
		# 与上一个点经纬度一的轨迹点，过滤掉。
		dev_data.loc[:,'lng_sub']=dev_data['lng']-dev_data['lng'].shift(1)
		dev_data.loc[:,'lat_sub']=dev_data['lat']-dev_data['lat'].shift(1)
		dev_data=dev_data.loc[(dev_data['lng_sub']!=0) & (dev_data['lat_sub']!=0)]
		# 还需要过滤，如果一个点，与上一个点和下一个点的根据距离计算出的瞬时速度超过正常值，且自身速度为零，去掉这个点
		
		# 轨迹点多的时候，传输时间过长，去掉不需要的字典，减少传输时间。
		dev_data=dev_data.drop(['lbs',
								'trail',
								'change_lnglat',
								'lng_sub',
								'lat_sub',
								'wifi',
								'rssi',
								'obd',
								'status',
								'blood_pres',
								'sos_alarm',
								'hard_verson',
								'step_count',
								'oil_use',
								'efence_alarm',
								'speed_alarm',
								'heart_rate',
								'heart_alarm',
								'blood_alarm',
								'location',
								'othermesg',
								'scanner'], axis=1)
		# print('dev_data========>11111',dev_data['dev_upload'],dev_data['serv_receive'],dev_data['lng'])
		
		dev_data=dev_data.drop_duplicates('serv_receive')
		# print('dev_data========>22222',dev_data)
		if dev_data.shape[0]>1:
			dev_data=json.loads(dev_data.to_json(orient="records",force_ascii=False))
		else:
			dev_data=[]

	else:
		dev_data=[]

	return dev_data


# 电子围栏页面

def handle_efence_by_mapkind(efe,map_kind,method='get'):
	# print('old==========>',efe)
	if method=='get':
		for x in range(len(efe)):
			efe[x]['content']=eval(efe[x]['content'])
			if efe[x]['kind']=='circle':
				centre=efe[x]['content'][1]
				if map_kind=='bd':
					efe[x]['content'][1]=wgs84_to_bd09(centre['lng'],centre['lat'])
				elif map_kind=='gd':
					efe[x]['content'][1]=wgs84_to_gcj02(centre['lng'],centre['lat'])

			elif efe[x]['kind'] in ['polygon','rectangle']:
				for y in range(len(efe[x]['content'])):
					if map_kind=='bd':
						efe[x]['content'][y]=wgs84_to_bd09(efe[x]['content'][y]['lng'],efe[x]['content'][y]['lat'])
					elif map_kind=='gd':
						efe[x]['content'][y]=wgs84_to_gcj02(efe[x]['content'][y]['lng'],efe[x]['content'][y]['lat'])
			efe[x]['content']=str(efe[x]['content'])

	elif method=='save':
		if efe['kind']=='circle':
			centre=efe['content'][1]
			if map_kind=='bd':
				efe['content'][1]=bd09_to_wgs84(centre['lng'],centre['lat'])
			elif map_kind=='gd':
				efe['content'][1]=gcj02_to_wgs84(centre['lng'],centre['lat'])

		elif efe['kind'] in ['polygon','rectangle']:
			for y in range(len(efe['content'])):
				if map_kind=='bd':
					efe['content'][y]=bd09_to_wgs84(efe['content'][y]['lng'],efe['content'][y]['lat'])
				elif map_kind=='gd':
					efe['content'][y]=gcj02_to_wgs84(efe['content'][y]['lng'],efe['content'][y]['lat'])

	# print('new==========>',efe)
	return efe
# 路线管理
def handle_polyline(efence_info,what,request,map_kind='bd'):
	res=base_respone()
	# 参数校验
	param_list=['name','kind','alarm_kind','content','s_time','e_time','device_id']
	if what=='del':
		param_list=['name']
	elif what=='phone_del':
		param_list=['name','device_id']
	efence_info=post_param_check(param_list,efence_info)
	if efence_info.get('param_error')!=None:
		res['error']=efence_info.get('param_error')
		res['code']=1234
		return res

	if what=='add':
		check_efe_name=Efence.objects.filter(name=efence_info['name']).first()
		# print(check_efe_name)
		if check_efe_name!=None:
			res['code']=1234
			res['error']='名称重复'
			return res

		efence_info=handle_efence_by_mapkind(efence_info,map_kind,'save')
		# 存储在device表格efence字段的内容{efence:efence_to_dev}
		efence_to_dev=efence_info.copy()
		efence_to_dev.pop('device_id')
		efence_to_dev.pop('content')
		efence_to_dev.pop('kind')
		efence_bind_dev=efence_info['device_id']
		efence_info['owner']=request.user
		efence_info['content']=str(efence_info['content'])
		efence_info['alarm_kind']=str(efence_info['alarm_kind'])
		efence_info['device_id']=str(efence_bind_dev)

		Efence.objects.create(**efence_info)
		# 每个设备只能绑定一条路线，
		for x in efence_bind_dev:
			Device.objects.filter(device_id=x).update(polyline=str(efence_to_dev))

		system_log(request,'新增路线-'+efence_info['name'])


	# 围栏信息修改
	elif what=='edit':

		efence_to_dev=efence_info.copy()
		new_bind_dev=efence_to_dev.pop('device_id')
		efence_to_dev.pop('content')
		efence_to_dev.pop('kind')
		efe_name=efence_info['name']
		old_bind_dev=Efence.objects.filter(name=efe_name).first()
		if old_bind_dev==None:
			res['code']=1234
			res['error']='路线不存在'
			return res
		old_bind_dev=eval(old_bind_dev.device_id)

		# 历遍围栏原有的绑定device，与新绑定的device对比
		if old_bind_dev!=[]:
			for x in old_bind_dev:
				# 原有的绑定device_id,不在新绑定的device_id列表里面的，路线清空
				if x not in new_bind_dev:
					Device.objects.filter(device_id=x).update(polyline='0')
					
		# 历遍围栏新绑定device，绑定新的路线
		if new_bind_dev!=[]:
			for x in new_bind_dev:
				Device.objects.filter(device_id=x).update(polyline=str(efence_to_dev))

		# 更新围栏列表里面的内容，存储在围栏变革里面的围栏数据，包含绑定的device_id列表
		efence_info['content']=str(efence_info['content'])
		efence_info['alarm_kind']=str(efence_info['alarm_kind'])
		efence_info['device_id']=str(efence_info['device_id'])
		Efence.objects.filter(name=efe_name).update(**(efence_info))
		system_log(request,'修改路线-'+efence_info['name'])
	# 围栏信息删除
	elif what=='del':
		efe_name=efence_info['name']
		old_bind_dev=Efence.objects.filter(name=efe_name).first()
		if old_bind_dev==None:
			res['code']=1234
			res['error']='路线不存在'
			return res
		old_bind_dev=eval(old_bind_dev.device_id)
		if old_bind_dev!=[] and old_bind_dev!=0:
			res['code']=1234
			res['error']='路线有绑定设备，无法进行删除操作。'
			return res
		else:
			Efence.objects.filter(name=efe_name).delete()
			system_log(request,'删除路线-'+efence_info['name'])


	return res

# 电子围栏
def handle_efence(efence_info,what,request,map_kind='bd'):
	res=base_respone()
	# 参数校验
	param_list=['name','kind','alarm_kind','content','s_time','e_time','device_id']
	if what=='del':
		param_list=['name']
	elif what=='phone_del':
		param_list=['name','device_id']
	efence_info=post_param_check(param_list,efence_info)
	if efence_info.get('param_error')!=None:
		res['error']=efence_info.get('param_error')
		res['code']=1234
		return res

	if what=='add':
		check_efe_name=Efence.objects.filter(name=efence_info['name']).first()
		# print(check_efe_name)
		if check_efe_name!=None:
			res['code']=1234
			res['error']='围栏名称重复'
			return res

		efence_info=handle_efence_by_mapkind(efence_info,map_kind,'save')
		# 存储在device表格efence字段的内容{efence:efence_to_dev}
		efence_to_dev=efence_info.copy()
		efence_to_dev.pop('device_id')
		efence_bind_dev=efence_info['device_id']
		efence_info['owner']=request.user
		efence_info['content']=str(efence_info['content'])
		efence_info['device_id']=str(efence_bind_dev)

		Efence.objects.create(**efence_info)

		for x in efence_bind_dev:
			efence=Device.objects.filter(device_id=x).first().efence
			if efence !='0':
				if isinstance(eval(efence),dict)==True:
					efence_detail=eval(efence)
					efence_detail[efence_info['name']]=efence_to_dev
					Device.objects.filter(device_id=x).update(efence=str(efence_detail))
				else:
					efence_detail={}
					efence_detail[efence_info['name']]=efence_to_dev
					Device.objects.filter(device_id=x).update(efence=str(efence_detail))

			else:
				efence_detail={}
				efence_detail[efence_info['name']]=efence_to_dev
				Device.objects.filter(device_id=x).update(efence=str(efence_detail))

		system_log(request,'新增围栏-'+efence_info['name'])


	# 围栏信息修改
	elif what=='edit':
		new_bind_dev=efence_info.pop('device_id')
		efence_info=handle_efence_by_mapkind(efence_info,map_kind,'save')
		efe_name=efence_info['name']
		old_bind_dev=Efence.objects.filter(name=efe_name).first()
		if old_bind_dev==None:
			res['code']=1234
			res['error']='围栏不存在'
			return res
		old_bind_dev=eval(old_bind_dev.device_id)

		# 历遍围栏原有的绑定device，与新绑定的device对比
		if old_bind_dev!=[]:
			for x in old_bind_dev:
				efence=Device.objects.filter(device_id=x).first()
				# 原有的device存在于新的绑定device列表里面，更新device的相应efence数据
				if x in new_bind_dev:
					if efence!=None:
						efence=eval(efence.efence)
						if isinstance(efence,dict)==True:
							for y in efence:
								if y==efe_name:
									efence[efe_name].update(efence_info)
									Device.objects.filter(device_id=x).update(efence=str(efence))
						else:
							new_bind_dev.remove(x)
				# 原有的device不存在于新的绑定device列表里面，解绑device的相应efence数据
				else:
					if efence!=None:
						efence=eval(efence.efence)
						efence.pop(efe_name)
						if efence=={}:
							efence='0'
						Device.objects.filter(device_id=x).update(efence=str(efence))

					
		# 历遍围栏新绑定device，与原有绑定的device对比
		if new_bind_dev!=[]:
			for x in new_bind_dev:
				# 新绑定的device不存在原有device列表里面的，为新增绑定device，对相应的device新增efence，
				if x not in old_bind_dev:
					efence=Device.objects.filter(device_id=x).first()
					if efence!=None:
						efence=efence.efence
						if efence !='0':
							efence=eval(efence)
							efence[efe_name]=efence_info
							Device.objects.filter(device_id=x).update(efence=str(efence))
						else:
							efence={}
							efence[efe_name]=efence_info
							Device.objects.filter(device_id=x).update(efence=str(efence))

		# 更新围栏列表里面的内容，存储在围栏变革里面的围栏数据，包含绑定的device_id列表
		efence_info['device_id']=str(new_bind_dev)
		Efence.objects.filter(name=efe_name).update(**(efence_info))
		system_log(request,'修改围栏-'+efence_info['name'])
	# 围栏信息删除
	elif what=='del':
		efe_name=efence_info['name']
		old_bind_dev=Efence.objects.filter(name=efe_name).first()
		if old_bind_dev==None:
			res['code']=1234
			res['error']='围栏不存在'
			return res
		old_bind_dev=eval(old_bind_dev.device_id)
		if old_bind_dev!=[] and old_bind_dev!=0:
			res['code']=1234
			res['error']='围栏有绑定设备，无法进行删除操作。'
			return res
		else:
			Efence.objects.filter(name=efe_name).delete()
			system_log(request,'删除围栏-'+efence_info['name'])

	# 手机删除围栏
	elif what=='phone_del':
		efe_name=efence_info['name']
		# 正在app操作的设备id
		current_dev=efence_info['device_id']
		old_bind_dev=Efence.objects.filter(name=efe_name).first()
		if old_bind_dev==None:
			res['code']=1234
			res['error']='围栏不存在'
			return res
		old_bind_dev=eval(old_bind_dev.device_id)
		# 围栏绑定的设备超过1个，不能删除
		if len(old_bind_dev)>1:
			res['code']=1234
			res['error']='围栏有绑定其他设备，请登录pc端操作。'
			return res
		else:
			# 围栏绑定的设备和正在app操作的设备不同，不能删除
			x=old_bind_dev[0]
			if x!=current_dev:
				res['code']=1234
				res['error']='围栏有绑定其他设备，请登录pc端操作。'
				return res
			efence=Device.objects.filter(device_id=x).first()
			if efence!=None:
				efence=eval(efence.efence)
				efence.pop(efe_name)
				if efence=={}:
					efence='0'
				Device.objects.filter(device_id=x).update(efence=str(efence))
			Efence.objects.filter(name=efe_name).delete()
			system_log(request,'手机app删除围栏-'+efe_name)

	return res

# from django.db.models import Q

@login_required
@csrf_exempt
def efence(request):
	res=base_respone()
	what=request.GET.get('what')
	map_kind=request.GET.get('map_kind')
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(str(request.user))

	if request.method=='GET':
		if what=='get_init_data':
			efence_data=list(Efence.objects.filter(owner__in=subordinate_user).exclude(kind='polyline').values())
			# print(efence_data)
			efence_data=handle_efence_by_mapkind(efence_data,map_kind)
			res['data']=efence_data
		return HttpResponse(json.dumps(res))

	if request.method=='POST':
		efence_info=eval(request.POST.get('base_info'))
		handle_result=handle_efence(efence_info,what,request,map_kind)
		if handle_result['code']==1000:
			efence_data=list(Efence.objects.filter(owner__in=subordinate_user).exclude(kind='polyline').values())
			efence_data=handle_efence_by_mapkind(efence_data,map_kind)
			handle_result['data']=efence_data
		return HttpResponse(json.dumps(handle_result))
		
	return render(request,'car_app/efence.html')



@login_required
@csrf_exempt
def polyline(request):
	res=base_respone()
	what=request.GET.get('what')
	map_kind=request.GET.get('map_kind')
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(str(request.user))

	if request.method=='GET':
		if what=='get_init_data':
			efence_data=list(Efence.objects.filter(owner__in=subordinate_user).filter(kind='polyline').values())
			# print(efence_data)
			efence_data=handle_efence_by_mapkind(efence_data,map_kind)
			res['data']=efence_data

		return HttpResponse(json.dumps(res))


	if request.method=='POST':
		efence_info=eval(request.POST.get('base_info'))
		handle_result=handle_polyline(efence_info,what,request,map_kind)
		if handle_result['code']==1000:
			efence_data=list(Efence.objects.filter(owner__in=subordinate_user).filter(kind='polyline').values())
			efence_data=handle_efence_by_mapkind(efence_data,map_kind)
			handle_result['data']=efence_data

		return HttpResponse(json.dumps(handle_result))
	
	return render(request,'car_app/polyline.html')

# 车辆运行统计
def handle_mileage_reports(device_ids,s_time,e_time):
	reports_data=[]
	for device_id in device_ids:

		repo_data={}
		repo_data['device_id']=device_id

		refresh_session(device_id)

		device=Device_Base.classes[device_id]
		dev_detail=session.query(device).filter(device.serv_receive>s_time).filter(device.serv_receive<e_time)
		# print('dev_detail',dev_detail.first())
		if dev_detail.first()!=None:
			#里程
			first_mileage=dev_detail.filter(device.mileage!='0').first()

			last_mileage=dev_detail.filter(device.mileage!='0').order_by(device.id.desc()).first()

			if first_mileage!=None and last_mileage!=None:
				# print(first_mileage.mileage,last_mileage.mileage)
				total_mileage=int(eval(last_mileage.mileage)['total_mileage'])-int(eval(first_mileage.mileage)['total_mileage'])
				repo_data['total_mileage']=total_mileage
			else:
				repo_data['total_mileage']='0'
			#停留时间
			stop_time=dev_detail.filter(device.stop_time!='0').all()
			all_stop=[]
			all_stop_time=0
			for x in stop_time:
				one_stop=eval(x.stop_time)
				if 'this_stoptime' in one_stop:
					all_stop_time+=int(one_stop['this_stoptime'])
				if one_stop['status']=='0':
					all_stop.append(one_stop)
			repo_data['all_stop_time']=round(all_stop_time/3600,2)
			repo_data['stop_time']=all_stop
			#行驶时间

			# s_drive=int(time.mktime(time.strptime(dev_detail.first().serv_receive, "%Y-%m-%d %H:%M:%S")))
			s_drive=int(time.mktime(time.strptime(dev_detail.first().serv_receive, "%Y-%m-%d %H:%M:%S")))
			e_drive=0
			if e_time!='' and e_time!='0':
				e_drive=int(time.mktime(time.strptime(e_time, "%Y-%m-%d %H:%M:%S")))
			now=int(time.time())
			if e_drive>now:
				e_drive=now
			drive_time=e_drive-s_drive-all_stop_time
			if drive_time<0:
				drive_time=0
			repo_data['drive_time']=round(drive_time/3600,2)
			#平均速度
			speed_aver=0
			try:
				speed_aver=total_mileage/drive_time*3600
			except:
				pass
			repo_data['speed']=speed_aver
			reports_data.append(repo_data)

	return reports_data
# @login_required
@csrf_exempt
def mileage_report(request):
	res = base_respone()
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	subordinate_user.append(str(request.user))
	what=request.GET.get('what')

	if request.method=='GET':
		if what=='get_init_data':
			subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
			subordinate_user.append(str(request.user))
			dev_id_list=Device.objects.filter(owner__in=subordinate_user).values('device_id')
			dev_id_list=pd.DataFrame(dev_id_list)
			dev_id_list=dev_id_list['device_id'].tolist()
			# print(dev_id_list)
			# 服务器的默认时区与中国时区相差16小时？？有待观察
			# 获取当天时间
			now = time.time()
			midnight = now - (now % 86400) + time.timezone
			# print(datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now)), "%Y-%m-%d %H:%M:%S"))
			pre_midnight = midnight - 86400
			now_midnight = midnight - 1
			s_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(pre_midnight)), "%Y-%m-%d %H:%M:%S")
			e_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_midnight)), "%Y-%m-%d %H:%M:%S")
			s_time=str(s_time)
			e_time=str(e_time)

			res['data']=handle_mileage_reports(dev_id_list,s_time,e_time)

			return HttpResponse(json.dumps(res))

	if request.method=='POST':
		if what=='query_report':
			query_param=eval(request.POST.get('base_info'))
			device_ids=query_param['hard_id']
			s_time=query_param['s_time']
			e_time=query_param['e_time']
			chose_time=query_param['chose_time']
			if chose_time!='0':
				now = time.time()
				midnight = now - (now % 86400) + time.timezone
				s_time = midnight - 86400*int(chose_time)
				s_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(s_time)), "%Y-%m-%d %H:%M:%S")
				s_time=str(s_time)
				# print(s_time,e_time)
			reports_data=handle_mileage_reports(device_ids,s_time,e_time)
			# print(json.dumps(reports_data))
			res['data']=reports_data
			return HttpResponse(json.dumps(res))

	return render(request,'car_app/mileage_report.html')

# 报警统计
@csrf_exempt
def alarm_report(request):
	what=request.GET.get('what')
	res=base_respone()
	if request.method=='GET':
		if what=='get_init_data':
			subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
			subordinate_user.append(str(request.user))
			dev_id_list=list(Device.objects.filter(owner__in=subordinate_user).values())
			dev_id_list=pd.DataFrame(dev_id_list)
			dev_id_list=dev_id_list['device_id'].tolist()
			# print(dev_id_list)
			# 服务器的默认时区与中国时区相差16小时？？有待观察
			# 获取当天时间
			time_data=time_cacu()
			s_time=time_data[0]
			e_time=time_data[1]

			reports_data=[]
			for device_id in dev_id_list:
				repo_data=alarm_statistic(device_id,s_time,e_time)
				package_data={'device_id':device_id,'analysis_time':[s_time,e_time]}
				package_data.update(repo_data)
				reports_data.append(package_data)
			# print('reports_data=====>',reports_data)
			res['data']=reports_data
			return HttpResponse(json.dumps(res))

	if request.method=='POST':
		if request.GET.get('what')=='query_report':
			query_param=eval(request.POST.get('base_info'))
			device_ids=query_param['hard_id']
			s_time=query_param['s_time']
			e_time=query_param['e_time']
			reports_data=[]
			
			for device_id in device_ids:
				repo_data=alarm_statistic(device_id,s_time,e_time)
				package_data={'device_id':device_id,'analysis_time':[s_time,e_time]}
				package_data.update(repo_data)
				reports_data.append(package_data)

			res['data']=reports_data
			return HttpResponse(json.dumps(res))

	return render(request,'car_app/alarm_report.html')

def time_cacu(days=1):
	now = time.time()
	midnight = now - (now % 86400) + time.timezone
	e_time=midnight
	s_time = midnight - 86400*int(days)

	s_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(s_time)), "%Y-%m-%d %H:%M:%S")
	e_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e_time)), "%Y-%m-%d %H:%M:%S")
	s_time=str(s_time)
	e_time=str(e_time)

	return [s_time,e_time]

# print(time_cacu(5))

# 设备运行统计
@csrf_exempt
def device_report(request):
	what=request.GET.get('what')
	res=base_respone()
	if request.method=='GET':
		if what=='get_init_data':
			subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
			subordinate_user.append(str(request.user))
			dev_id_list=list(Device.objects.filter(owner__in=subordinate_user).values())
			dev_id_list=pd.DataFrame(dev_id_list)
			dev_id_list=dev_id_list['device_id'].tolist()
			# print(dev_id_list)
			# 服务器的默认时区与中国时区相差16小时？？有待观察
			repo_obj=[]
			time_data=time_cacu()
			s_time=time_data[0]
			e_time=time_data[1]
			for device_id in dev_id_list:
				refresh_session(device_id)
				repo_data=device_statistic(device_id,s_time,e_time)
				print(repo_data)
				package_data={'device_id':device_id,'analysis_time':[s_time,e_time]}
				package_data.update(repo_data)
				repo_obj.append(package_data)

			# print(repo_obj)
			res['data']=repo_obj
			return HttpResponse(json.dumps(res))

	if request.method=='POST':
		if what=='query_report':
			query_param=eval(request.POST.get('base_info'))
			device_ids=query_param['hard_id']
			s_time=query_param['s_time']
			e_time=query_param['e_time']
			chose_time=query_param['chose_time']
			if chose_time!='0':
				now = time.time()
				midnight = now - (now % 86400) + time.timezone
				s_time = midnight - 86400*int(chose_time)
				s_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(s_time)), "%Y-%m-%d %H:%M:%S")
				s_time=str(s_time)
				# print(s_time,e_time)
			elif chose_time=='1':
				time_data=time_cacu()
				s_time=time_data[0]
				e_time=time_data[1]
			reports_data=[]
			reports_detail={}
			for device_id in device_ids:
				refresh_session(device_id)
				repo_data=device_statistic(device_id,s_time,e_time)

				package_data={'device_id':device_id,'analysis_time':[s_time,e_time]}
				package_data.update(repo_data)
				reports_data.append(package_data)
				
			# print(json.dumps(reports_data))
			res['data']=reports_data
			return HttpResponse(json.dumps(res))


	return render(request,'car_app/device_report.html')


def store_picture(base64data,folder_name,file_name):
	# print(folder_name)

	param_data=base64data.split(',')[1]
	img = base64.b64decode(param_data)
	# file_folder={'person':'person/','car':'car/','building':'building/','map':'map/','scanner':'scanner/'}
	# 创建路径，有的话不用理会
	sys_platform=sys.platform[0:3]

	path=''
	if sys_platform=='win':
		path=BASE_DIR+'\\car_app\\static\\data_from_web\\picture\\'+folder_name+'\\'
	else:
		path=BASE_DIR+'/car_app/static/data_from_web/picture/'+folder_name+'/'

	if not os.path.exists(path):
		os.makedirs(path)

	file_name=file_name+'_picture.png'
	img_name=path+file_name

	# print(img_name,type(img_name))
	fh = open(img_name,"wb")
	fh.write(img)
	fh.close()
	# src_path='/static/data_from_web/picture/'+folder_name+'/'+file_name+'_picture.png'
	return file_name

def remove_picture(folder,name):
	sys_platform=sys.platform[0:3]

	path=''
	if sys_platform=='win':
		path=BASE_DIR+'\\car_app\\static\\data_from_web\\picture\\'+folder+'\\'+name+'_picture.png'
	else:
		path=BASE_DIR+'/car_app/static/data_from_web/user/'+folder+'/'+name+'_picture.png'

	if os.path.exists(path):
		os.remove(path)













# 独立接口
# 登录接口
class LoginView(APIView):

	def post(self, request):
		"""
		前端接收用户名跟密码
		到数据库中校验用户名跟密码
		校验通过将成功信息返回给前端
		{
			"user":{
				"username":"hanlei",
				"password":"hanleilei"
			}
		}
		"""
		result=login_func(request)
		# print(result)
		return Response(result)

# 首页数据
def get_base_info(username,sub_user_result,map_kind='bd'):
	sub_user=sub_user_result[0]
	user_tree=sub_user_result[1]
	all_user=sub_user.copy()
	all_user.append(username)
	device=get_device_detail(all_user,map_kind)
	alarm_data=get_alarm_data(all_user)
	if len(alarm_data)>0:
		alarm_data=pd.DataFrame(alarm_data)
		alarm_data['location']=alarm_data['location'].map(lambda x:eval(x) if x!='0' or x!='' else x)
		alarm_data=json.loads(alarm_data.to_json(orient="records",force_ascii=False))
	sub_user_detail=list(Myuser.objects.filter(username__in=sub_user).values())
	all_data={'device':device,'alarm_data':alarm_data,'sub_user_detail':sub_user_detail,'user_tree':user_tree}

	return all_data

class BaseInfo(APIView):

	def post(self, request):
		
		# 校验参数

		param=check_api_param(request)
		if param['code']!=1000:
			return Response(param)

		
		handle_data=request.data.get('data')
		res=base_respone()
		res['msg']='数据加载成功'
		user=param['data']['user']
		what=param['data']['what']
		map_kind=param['data']['map_kind']
		sub_user_result=get_subordinate_user(user,Myuser)
		sub_user=sub_user_result[0]
		user_tree=sub_user_result[1]
		all_user=sub_user.copy()
		all_user.append(user)

		# 加载index的数据，device，alarm_data,building,scanner,map_data,subordinate_user_detail
		if what=='get_init_data':
			init_data=get_base_info(user,sub_user_result,map_kind)
			res['data']=init_data
			# print('data==>',res)
			return Response(res)

		elif what=='get_base_refresh':
			device=get_device_detail(all_user,map_kind)
			alarm_data=get_alarm_data(all_user)
			result={'device':device,'alarm_data':alarm_data}
			res['data']=result
			return Response(res)

		elif what=='get_refresh_device':
			device=get_device_detail(all_user,map_kind)
			res['data']=device
			return Response(res)

		elif what=='get_refresh_alarm':
			alarm_data=get_alarm_data(all_user)
			if len(alarm_data)>0:
				alarm_data=pd.DataFrame(alarm_data)
				alarm_data['location']=alarm_data['location'].map(lambda x:eval(x) if x!='0' or x!='' else x)
				alarm_data=json.loads(alarm_data.to_json(orient="records",force_ascii=False))

			if len(alarm_data)==0:
				dev=Device.objects.filter(owner__in=all_user).first()
				pt=simulate_point(dev.device_id)
				ln={'satelite':[pt['lng'],pt['lat']]}
				# ln={'wifi': "[{'ssid': 'a', 'mac': '78:f5:57:0a:ef:44', 'rssi': '61'}, {'ssid': 'a', 'mac': '78:f5:57:0a:ef:44', 'rssi': '61'}, {'ssid': 'a', 'mac': '78:58:60:99:ac:6c', 'rssi': '57'}]"}
				alarm_data=[{'name':'circleefence001',
							'device_id':dev.device_id,
							'location':ln,
							'content':'模拟数据',
							'kind':'circle',
							's_time':'0',
							'e_time':'0',
							'handle':'no',
							'remark':'0',
							'owner':'demo',
							'id':1}]
			res['data']=alarm_data
			return Response(res)

		elif what=='get_wifi_lbs_addr':

			track_type=handle_data.get('track_type')
			device_id=handle_data.get('device_id')
			track_data=handle_data.get('track_data')
			address_result=eval('get_'+track_type+'_address('+track_data+','+device_id+')')
			# print('address=====',address_result)
			address='0'
			if address_result!='':
				loca=address_result[2]
				if isinstance(loca,dict):
					loca=loca['desc']
				else:
					loca=eval(loca)
					loca=loca['desc']

				if map_kind=='bd':
					lnglat=wgs84_to_bd09(float(address_result[0]),float(address_result[1]))
				elif map_kind=='gd':
					lnglat=wgs84_to_gcj02(float(address_result[0]),float(address_result[1]))

				address={'lng':lnglat['lng'],'lat':lnglat['lat'],'location':loca}

			res['data']=address

			return Response(res)

		elif what=='handle_alarm':

			handle_result=handle_alarm(request,handle_data)

			return Response(handle_result)

		# 修改密码
		elif what=='handle_password':

			handle_result=handle_password(request,handle_data)

			return Response(handle_result)

		# 修改登录用户信息
		elif what=='handle_user_self':
			param_list=['kind','user_icon','refresh_time','alarm_audio','alarm_show']
			character=handle_data.get('character')
			character=eval(character)
			character=post_param_check(param_list,character)
			# print('character====>',character)
			if character.get('param_error')!=None:
				res=base_respone()
				res['error']=str(character.get('param_error'))
				res['code']=1234
				return Response(res)

			# print('handle_data====>',handle_data)
			handle_result=database_handle('登录用户','edit',Myuser,'username',handle_data,[],user)

			return Response(handle_result)

		else:
			res['error']='what:'+str(what)+'-找不到对应项目'
			res['code']=1234
			return Response(res)

class DynamicApi(APIView):
	
	def post(self, request):
		# print('dynamic==>',request)
		# 校验参数
		param=check_api_param(request)
		if param['code']!=1000:
			# print('param==>',param)
			return Response(param)

		res=base_respone()
		user=param['data']['user']
		what=param['data']['what']
		map_kind=param['data']['map_kind']
		handle_data=request.data.get('data')
		#报警参数设置数据处理（系统参数设定，绑定设备，不改变硬件本身的参数）
		if what=='alarm_set':
			device_id=handle_data['device_id']
			handle_result=handle_param_set(handle_data,request,[user])
			res_data=Device.objects.filter(device_id=device_id).first()
			res_data=vars(res_data)
			res_data.pop('_state')
			res_data=pd.DataFrame([res_data])
			res_data=handle_dynamic_data(res_data,map_kind)
			handle_result['data']=res_data[0]
			# print('res_data==>',res_data)
			return Response(handle_result)
			

		#设备硬件参数设置（给设备发指令，改变硬件本身的参数）
		elif what=='device_set':
			
			handle_result=handle_command(handle_data,user,'device_set')

			return Response(handle_result)

		#给设备下发命令
		elif what=='order_down':
			# print('order_down==>',handle_data)
			handle_result=handle_command(handle_data,user,'order')
			# print('handle_result==>',handle_result)

			return Response(handle_result)

		elif what=='tracking':
			handle_data['map_kind']=map_kind
			handle_result=handle_tracking(handle_data)
			# 模拟数据	
			if handle_result['error']=='设备尚未启用':
				handle_result['code']=1000
				handle_result['data']=simulate_point(handle_data['device_id'])

			return Response(handle_result)

		else:
			res['error']='what:'+str(what)+'-找不到对应项目'
			res['code']=1234
			return Response(res)

class QueryApi(APIView):
	def post(self, request):
		# print('dynamic==>',request)
		# 校验参数
		param=check_api_param(request)
		if param['code']!=1000:
			print('param==>',param)
			return Response(param)

		res=base_respone()
		user=param['data']['user']
		what=param['data']['what']
		map_kind=param['data']['map_kind']
		handle_data=request.data.get('data')
		#报警参数设置数据处理（系统参数设定，绑定设备，不改变硬件本身的参数）
		if what=='query_trail':
			handle_data['map_kind']=map_kind
			handle_result=handle_trail(handle_data)

			if len(handle_result)==0:
				for x in range(40):
					handle_result.append(simulate_point(handle_data['device_id']))
			res['data']=handle_result
			return Response(res)

		else:
			res['error']='what:'+str(what)+'-找不到对应项目'
			res['code']=1234
			return Response(res)

# 电子围栏
class EfenceApi(APIView):

	def post(self, request):
			# print('dynamic==>',request)
			# 校验参数
		param=check_api_param(request)
		if param['code']!=1000:
			print('param==>',param)
			return Response(param)
		res=base_respone()
		user=param['data']['user']
		what=param['data']['what']

		
		map_kind=param['data']['map_kind']
		handle_data=request.data.get('data')

		if what=='get_efence':
			subordinate_user=get_subordinate_user(user,Myuser)[0]
			subordinate_user.append(user)
			efence_data=list(Efence.objects.filter(owner__in=subordinate_user).values())
			# print(efence_data)
			efence_data=handle_efence_by_mapkind(efence_data,map_kind)
			res['data']=efence_data
			return Response(res)
		elif what=='get_efence_by_name':
			efence_data=[]
			for x in handle_data:
				efe=Efence.objects.filter(name=str(x)).first()
				if efe!=None:
					efe=vars(efe)
					efe.pop('_state')
					efence_data.append(efe)
			handle_result = handle_efence_by_mapkind(efence_data,map_kind)[0]
			handle_result['content']=eval(handle_result['content'])
			res['data']=handle_result
			return Response(res)
		else:
			handle_result = handle_efence(handle_data,what,request,map_kind)

			if handle_result['code']==1000:
				if what=='phone_del':
					handle_result['data']=handle_data['name']
				else:
					efence_data=list(Efence.objects.filter(name=handle_data['name']).values())
					efence_data=handle_efence_by_mapkind(efence_data,map_kind)
					efence_data[0]['content']=eval(efence_data[0]['content'])
					handle_result['data']=efence_data[0]

			return Response(handle_result)
# 车务管理API
class CarApplyApi(APIView):

	def post(self, request):
			# print('dynamic==>',request)
			# 校验参数
		param=check_api_param(request)
		if param['code']!=1000:
			print('param==>',param)
			return Response(param)
		res=base_respone()
		user=param['data']['user']
		what=param['data']['what']
		map_kind=param['data']['map_kind']
		handle_data=request.data.get('data')

		handle_result=handle_car_apply(what,user,handle_data)
		if handle_result['code']==1000:
			apply_data=handle_result['data']
			if len(apply_data)>0:
				apply_data=pd.DataFrame(apply_data)
				apply_data['param_set']=apply_data['param_set'].map(lambda x:eval(x))
				apply_data=json.loads(apply_data.to_json(orient="records",force_ascii=False))
				handle_result['data']=apply_data


		return Response(handle_result)

class CarApproveApi(APIView):

	def post(self, request):
			# print('dynamic==>',request)
			# 校验参数
		param=check_api_param(request)
		if param['code']!=1000:
			print('param==>',param)
			return Response(param)
		# res=base_respone()
		user=param['data']['user']
		what=param['data']['what']
		map_kind=param['data']['map_kind']
		handle_data=request.data.get('data')
		if what=='get_init_data':
			handle_data=''
		handle_result=handle_car_apporve(what,user,handle_data)
		
		if handle_result['code']==1000:
			apply_data=handle_result['data']['apply_data']
			if len(apply_data)>0:
				apply_data=pd.DataFrame(apply_data)
				apply_data['param_set']=apply_data['param_set'].map(lambda x:eval(x))
				apply_data=json.loads(apply_data.to_json(orient="records",force_ascii=False))
				handle_result['data']['apply_data']=apply_data


		return Response(handle_result)


# 用户数据管理
class UserManage(APIView):

	def post(self,request):
		res=base_respone()
		param=check_api_param(request)
		result=BaseResponse()
		if param['code']!=1000:
			result.code=1234
			result.error='token错误'
			return Response(result.dict)
		request.user=username
		what=request.data.get('what','')
		handle_data=eval(request.data.get('handle_data',''))
		# print('handle',handle_data)
		result.data=user_manage_func(request,handle_data,what,Myuser)
		return Response(result.dict)


# 操作日志记录
def system_log(request,content,result='success'):
	username=str(request.user)
	owner=str(request.user)
	visible_name=''
	if Myuser.objects.filter(username=username).first()==None:
		owner='admin'
		visible_name=''
	else:
		visible_name=Myuser.objects.filter(username=username).first().visible_name
	log_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	log_dict={'username':username,'visible_name':visible_name,'remark':'0','content':content,'result':result,'owner':username,
			  'date_added':log_time}
	Sys_Log.objects.create(**(log_dict))



# 登录处理函数
def login_func(request):
	res=base_respone()
	user = request.data
	# print('user==>',user)
	username=''
	password=''
	if user:
		username = user.get("username", "")
		password = user.get("password", "")
		if username and password != "":
			user_obj = authenticate(username=username, password=password)
			# print(user_obj)
			if user_obj is not None:
				# 查看是否是停用账户
				user_detail=Myuser.objects.filter(username=username).first()
				if user_detail.status == "off":
					res['code'] = 10234
					res['error'] = "此账号已被停用,请确认之后登录"
				else:
					# 记录日志
					request.user=username
					token = str(uuid.uuid4())
					# 将用户username以及token值存入redis,并且设置有效期为7天
					mesg_redis.set(token, username, ex=datetime.timedelta(days=7))
					# 获取此用户的权限
					user_self=vars(user_detail)
					user_self.pop('_state')
					character=user_self.pop('character')
					character=eval(character)
					all_data={"token": token, "user_self": user_self, "character": character}
					res['data'] = all_data
					# print('res==>',res)
			else:
				# 用户密码校验不成功
				res['error'] = "用户名或密码错误"
				res['code'] = 1011
	else:
		res['error'] = "未携带用户名和密码"
		res['code'] = 1010

	log_content=username+'-用户登录'
	log_res='成功'
	if res['error']!='':
		log_content=res['error']
		log_res='失败'

	system_log(request,log_content,log_res)

	return res

def get_user_tree(user,Myuser,user_tree,subordinate_user):
	# print('user======>',user)
	user_datail=Myuser.objects.filter(username=user).first()
	if user_datail!=None:
		visible_name=user_datail.visible_name
		level=user_datail.subordinate
		user_id=user_datail.id
		sub_data={"id":user_id,'name':user,"title":visible_name, "children":[],'spread':'true'}
		user_tree.append(sub_data)

		if level!='0':
			level=level.split(',')
			for x in level:
				subordinate_user.append(x)
				get_user_tree(x,Myuser,user_tree[-1]['children'],subordinate_user)

def get_subordinate_user(user,Myuser):
	user_tree=[]
	# 下级用户列表
	subordinate_user=[]
	# 获取用户的树状结构信息，并把下级用户信息加入subordinate_user列表
	get_user_tree(user,Myuser,user_tree,subordinate_user)
	# 获取下级用户信息
	return [subordinate_user,user_tree]

# 从token取用户名
def check_token(request):
	result=base_respone()
	token = request.data.get("token", "")
	username=mesg_redis.get(token)
	return username

# 参数校验
def check_api_param(request):

	result=base_respone()
	param=request.data.get('param')

	if param==None or param=='':
		result['code']=1234
		result['error']='参数缺失：'
		return result

	token = param.get("token", "")
	username=mesg_redis.get(token)
	param['user']=username
	request.user=username
	result['data']={'user':'','map_kind':'','what':''}
	for x in result['data']:
		value=param.get(x)
		if	value==None:
			result['code']=1234
			result['error']='参数缺失：'+x
			return result
		else:
			result['data'][x]=value
	return result

def get_device_detail(subordinate_user,map_kind='bd'):
	# 读取该用户和下属用户的所有设备信息
	sql_device = 'select * from car_app_device'
	device = pd.read_sql_query(sql_device,engine)
	# 判断是否有device
	if device.shape[0]>0:
		# 判断该用户名下是否有设备
		device_data=device.loc[(device['owner'].isin(subordinate_user)) & (device['dynamic']!='0')].copy()
		if device_data.shape[0]>0:
			device_data=handle_dynamic_data(device_data,map_kind)
			return device_data
	return []

def handle_dynamic_data(device_data,map_kind=''):

	# 加载未处理的报警信息，用于报警更新

	sql_alarm='select * from car_app_alarm where handle=\'no\''
	alarm_detail=pd.read_sql_query(sql_alarm,engine)
	alarm_unhandle=alarm_detail['device_id'].tolist()

	# 设备的使用者信息，字符串转换为字典
	def hanle_user_detail(data):
		if data=='' or data=='0' or data==0 :
			data={"customize_title1":"","customize_title2":"","customize_title3":"","customize_value1":"","customize_value2":"","customize_value3":"","icon":"default"}
		else:
			data=eval(data)
		return data
	device_data['user_detail']=device_data['user_detail'].map(lambda x:hanle_user_detail(x))
	# device_data['user_detail']=device_data['user_detail'].map(lambda x:x['current'] if isinstance(x,dict)==True else x)
	# 设备的参数设置信息，字符串转换为字典
	device_data['param_set']=device_data['param_set'].map(lambda x:eval(x))
	device_data['efence']=device_data['efence'].map(lambda x:eval(x))
	# 设备的最新更新信息进行处理,字符串转换为字典,位置,在线状态,报警状态,设备自身状态等进行处理
	device_data['dynamic']=device_data['dynamic'].map(lambda x:eval(x))
	# 未启用的设备，用模拟位置点
	device_data['dynamic']=device_data.apply(lambda x:simulate_point(x['device_id']) if x['dynamic']['lng']=='0' else x['dynamic'],axis=1)
	# 位置信息
	# 1、卫星定位
	device_data.loc[:,'lng']=device_data['dynamic'].map(lambda x:x['lng'])
	device_data.loc[:,'lat']=device_data['dynamic'].map(lambda x:x['lat'])
	# 2、lbs定位，wifi定位
	device_data.loc[:,'wifi_address']=device_data['dynamic'].map(lambda x:get_wifi_address(x['wifi'],x['device_id']) if x['track_type']=='wifi' else '0')
	device_data['lng']=device_data.apply(lambda x:float(x['wifi_address'][0]) if x['dynamic']['track_type']=='wifi' and x['wifi_address'][0]!='0' else x['lng'],axis=1)
	device_data['lat']=device_data.apply(lambda x:float(x['wifi_address'][1]) if x['dynamic']['track_type']=='wifi' and x['wifi_address'][1]!='0'else x['lat'],axis=1)
	device_data.loc[:,'lbs_address']=device_data['dynamic'].map(lambda x:get_lbs_address(x['lbs'],x['device_id']) if x['track_type']=='lbs' else '0')
	device_data['lng']=device_data.apply(lambda x:float(x['lbs_address'][0]) if x['dynamic']['track_type']=='lbs' else x['lng'],axis=1)
	device_data['lat']=device_data.apply(lambda x:float(x['lbs_address'][1]) if x['dynamic']['track_type']=='lbs' else x['lat'],axis=1)
	# 坐标系转换bd:百度,gd:高德
	if map_kind=='bd':
		device_data.loc[:,'change_lnglat']=device_data.apply(lambda x:wgs84_to_bd09(x['lng'],x['lat']) if x['lng']!='0' else '0',axis=1)
	elif map_kind=='gd':
		device_data.loc[:,'change_lnglat']=device_data.apply(lambda x:wgs84_to_gcj02(x['lng'],x['lat']) if x['lng']!='0' else '0',axis=1)
	# print(device_data['change_lnglat'])
	device_data['lng']=device_data.apply(lambda x:x['change_lnglat']['lng'] if x['change_lnglat']!='0' else x['lng'],axis=1)
	device_data['lat']=device_data.apply(lambda x:x['change_lnglat']['lat'] if x['change_lnglat']!='0' else x['lat'],axis=1)
	

	# 在线状态，在线，离线，休眠
	now=int(time.time())

	device_data['serv_receive']=device_data['dynamic'].map(lambda x:'2000-01-01 01:01:01' if x['serv_receive']=='0' else x['serv_receive'])
	device_data.loc[:,'on_off_line']=device_data['dynamic'].map(lambda x:x['on_off_line'] if x.get('on_off_line')!=None else 'offline')
	# 超过15分钟没数据，判断为离线,因为部分设备链接断开也不会提示
	device_data['on_off_line']=device_data.apply(lambda x:'offline' if x['on_off_line']=='online' and now-time.mktime(time.strptime(x['serv_receive'],'%Y-%m-%d %H:%M:%S'))>900 else x['on_off_line'],axis=1)
	# 在线，且超过数据发送间隔超过300秒，视为休眠
	device_data['sleep_status']=device_data.apply(lambda x:'sleep' if x['on_off_line']=='online' and now-time.mktime(time.strptime(x['serv_receive'],'%Y-%m-%d %H:%M:%S'))>300 else 'no',axis=1)
	# 设备状态，acc，定位与否等
	device_data['status']=device_data['status'].map(lambda x:eval(x) if x!='0' else [])
	device_data.apply(lambda x:x['status'].append(x['on_off_line']),axis=1)
	device_data.apply(lambda x:x['status'].append(x['sleep_status']) if x['sleep_status']!='no' else None,axis=1)
	# 报警状态，需要读取数据库，数据库读取的效率大概为1000次/秒，数量大了影响速度，以后改进
	device_data.loc[:,'alarm_status']=device_data['device_id'].map(lambda x:'alarm' if x in alarm_unhandle else 'no')
	# device_data['iccid']=device_data['iccid'].map(lambda x:str(x))
	# 电量、rssi信号
	device_data.loc[:,'battery']=device_data['dynamic'].map(lambda x:x['battery'])
	device_data.loc[:,'rssi']=device_data['dynamic'].map(lambda x:x['rssi'])
	device_data=device_data.drop(['change_lnglat'], axis=1)
	# device_data=device_data.drop(['dynamic','wifi_address','lbs_address','change_lnglat'], axis=1)
	# user_device=device_data.groupby('owner')['owner'].count()
	# print('user_device====>',user_device)
	device_data=json.loads(device_data.to_json(orient="records",force_ascii=False))

	return device_data

# 根据用户类型取数据，常规用户数据依据设备OWNER来区分，手机注册用户绑定的设备，在character里面
def get_alarm_data(subordinate_user):
	alarm_data=[]
	dev = list(Device.objects.filter(owner__in=subordinate_user).values())
	dev=pd.DataFrame(dev)
	if dev.empty==False:
		dev_ids=dev['device_id'].tolist()
		alarm_data=list(Alarm.objects.filter(device_id__in=dev_ids).filter(handle='no').values())

	return alarm_data

# print(dir(Car._meta))
# print(Car._meta.get_fields())
# print('owner' in Car._meta.local_fields)
# print(vars(Car.objects.model))
# 增删改查函数
def database_handle(title,what,table,field,handle_data,subordinate_user,current_user):
	# print('handle_data====>',handle_data)
	# 获取
	table_field=table._meta.local_fields
	fields_list=[]
	for x in table_field:
		fields_list.append(x.name)
	res = base_respone()
	key_word=''
	if what!='add_from_file':
		# 校验参数
		key_word=handle_data.get(field)
	else:
		key_word=handle_data
	target_user=''
	# 单个新增
	if what=='add':
		# 重名判断
		# key_word=handle_data[field]
		
		if table.objects.filter(**({field:key_word})).first()!=None:
			res['code']=1234
			res['error']=key_word+'已存在，请使用其他名称/id'
		else:
			if 'date_added' in fields_list:
				handle_data['date_added']=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
			table.objects.create(**(handle_data))

	# 设备通过文件批量新增
	elif what=='add_from_file':
		obj_list=[]
		for add_data in handle_data:
			key_w=add_data.get(field)
			if table.objects.filter(**({field:key_w})).first()!=None:
				res['code']=1234
				res['error']=key_w+'已存在，请使用其他名称/id'
			else:
				if 'owner' in fields_list:
					owner=add_data.get('owner')
					if owner==None or owner not in subordinate_user:
						add_data['owner']=current_user
				if 'date_added' in fields_list:
					handle_data['date_added']=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
				obj=table(**add_data)
				obj_list.append(obj)

		table.objects.bulk_create(obj_list)
			
	# 编辑修改
	elif what=='edit':
		# key_word=handle_data.pop(field)
		table.objects.filter(**({field:key_word})).update(**(handle_data))

	# 删除
	elif what=='del':
		# key_word=handle_data.pop(field)
		table.objects.filter(**({field:key_word})).delete()
	# 转移
	elif what=='change_owner':
		# key_word=handle_data[field]
		target_user=handle_data['target_user']
		for n in key_word:
			table.objects.filter(**({field:n})).update(owner=target_user)

	result='failed'
	if(res['code']==1000):
		send_data=''
		if field=='username':
			if current_user in subordinate_user:
				subordinate_user.remove(current_user)
			subordinate_user.append(key_word)
			send_data=list(table.objects.all().filter(username__in=subordinate_user).values())
		else:
			send_data=list(table.objects.all().filter(owner__in=subordinate_user).values())
		res['data']=send_data
		result='success'

	# 记录操作日志
	# print('target_user====>',,target_user,handle_data)
	handle_kind_list={'add':'新增'+title+':'+str(key_word),'add_from_file':'批量新增'+title+':'+str(key_word),'edit':'修改'+title+':'+str(key_word),'del':'删除'+title+':'+str(key_word),'change_owner':'转移'+title+':'+str(key_word)+'到'+target_user}
	log_content=handle_kind_list[what]
	visible_name=Myuser.objects.filter(username=current_user).first().visible_name
	log_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	log_dict={'username':current_user,'visible_name':visible_name,'remark':'0','content':log_content,'result':result,'owner':current_user,
			  'date_added':log_time}
	Sys_Log.objects.create(**(log_dict))

	return res

def user_manage_func(request,handle_data,what,Myuser):
	res = base_respone()
	subordinate_user=get_subordinate_user(str(request.user),Myuser)[0]
	# print('subordinate_user',subordinate_user)
	if what=='add':
		# 增加数据
		handle_data['leader']=str(request.user)
		handle_result=database_handle('子用户',what,Myuser,'username',handle_data,subordinate_user,request.user)
		# 在django自带的user里面创建用户，用户登录和登出的操作
		User.objects.create_user(username=handle_data['username'],password='123456')
		# 把新建的子账号添加到子用户列表
		old_subordinate=Myuser.objects.filter(username=request.user).first().subordinate
		if old_subordinate=='0':
			Myuser.objects.filter(username=request.user).update(subordinate=handle_data['username'])
		else:
			Myuser.objects.filter(username=request.user).update(subordinate=old_subordinate+','+handle_data['username'])
		subordinate_user.append(handle_data['username'])
		user_data=list(Myuser.objects.filter(username__in=subordinate_user).values())
		handle_result['data']=user_data
		return handle_result
		

	# 修改数据
	elif what=='edit':
		handle_result=database_handle('子用户',what,Myuser,'username',handle_data,subordinate_user,request.user)
		return handle_result
		
	# 重置密码
	elif what=='reset_pwd':
		
		user = User.objects.get(username=handle_data['username'])
		if user is not None:
			user.set_password('123456')
			user.save()
			res['data']='重置密码成功,新密码：123456'
		else:
			res['code']=1234
			res['data']='重置密码失败'

		system_log(request,'重置密码-'+handle_data['username'],res['data'])

		return res


	#用户启用停用处理
	elif what=='user_status':
		handle_data=eval(request.POST.get('base_info'))
		title=''
		if handle_data['status']=='on':
			title='停用账号-'+handle_data['username']
			User.objects.filter(username=handle_data['username']).update(is_active=False)
			Myuser.objects.filter(username=handle_data['username']).update(status='off')
		else:
			title='启用账号-'+handle_data['username']
			User.objects.filter(username=handle_data['username']).update(is_active=True)
			Myuser.objects.filter(username=handle_data['username']).update(status='on')

		user_data=list(Myuser.objects.all().filter(username__in=subordinate_user).values())
		res['data']=user_data
		system_log(request,title)
		return res

#刷新数据库连接
def refresh_session(device_id):
	global Device_Base
	if not Device_Base.classes.has_key(device_id):
		engine = create_engine('sqlite:///car.db')    
		Device_Base = automap_base()
		Device_Base.prepare(engine, reflect=True)
	return

#自动加载command文件夹里面的所有command命令文档，存储为字典{厂家型号：命令函数（）}，
#例如{'vk':lambda device_id,kind,param,model:vk_command(device_id,kind,param,model)}

def log_write(data):#日志log存储
	with open('data_handle/sys_log/import_command_log','a') as f:
		f.write(data)
		f.write('&&')

command={}
def impfile(filename):
	filelist,*_ = os.walk(filename,topdown=True)
	*_,filenames = filelist
	for i in filenames:
		print(i)
		if i[-3:] == '.py' and i != '__init__.py':
			try:
				# device_model=re.search(r'(?P<model>\w*)_',i).group('model')
				model_name=i[:-3].split('_')[0]
				exc = 'from '+ 'data_handle.command'+'.'+i[:-3] + ' import '+ i[:-3]
				exec(exc,globals())
				# command[device_model]=lambda device_id,kind,param,model:eval(i[:-3])(device_id,kind,param,model)
				command[model_name]=i[:-3]
			except Exception as e:
				print('failed==>',i,e)
				log_data=str([i,e,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')])
				log_write(log_data)
#命令函数目录名
impfile('data_handle/command')
print('command==>',command)

# 命令处理，获取命令信息，
def handle_command(param_data,owner,command_style):
	print('handle_command==>',param_data,owner,command_style)
	result='0'

	if param_data.get('send_time')==None:
		param_data['send_time']=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

	res=base_respone()
	# 命令下发的必要参数取并校验
	param_list=['device_id','set_command','set_value','send_time','port']
	for x in param_list:
		if param_data.get(x)==None:
			res['code']=1234
			res['error']=str(x)+'-参数错误，错误值-'+str(param_data[x])
			return res
		if x!='set_value':
			if param_data.get(x)=='' or param_data.get(x)=='0' or param_data.get(x)==0:
				res['code']=1234
				res['error']=str(x)+'-参数错误，错误值-'+str(param_data[x])
				return res

	dev_id=str(param_data['device_id'])#谜题-在interact.html里面该参数为string，一模一样的命令下发代码，在dynamic页面中，该参数到这里变成了num，之前都是正常的
	comd=param_data['set_command']
	value=param_data['set_value']
	send_time=param_data['send_time']
	port=param_data['port']#接收的端口和设备品牌
	
	device_model=port[1]
	port=port[0]
	if device_model in command:
		param=eval(command[device_model]+'(dev_id,comd,value,device_model,owner)')
		print(param)
		# 设备不支持的命令，不用建立command_log表格
		if param=='':
			res['code']=1234
			res['error']='不支持的命令'
		else:
			
			# 命令log存库的名称
			comd_id=dev_id+comd+send_time
			# 图片和语音的数据量较大，本地文件存储，数据库存储文件路劲，在执行完毕的时候存储
			comd_log_value=value
			if comd in ['voice','picture']:
				comd_log_value=''
			# 命令执行记录
			comd_log=dict(command_id=comd_id,
							device_id=dev_id,
							command_name=comd,
							command_style=command_style,
							command_value =comd_log_value,
							send_time=send_time,
							owner=owner)
			Command_Log.objects.create(**(comd_log))
			comd_table_id=Command_Log.objects.get(command_id=comd_id).id
			# 命令表完整放到redis，供analysis模块执行完毕相应命令的是，更新执行结果
			command_detail={'id':comd_table_id,'command_id':comd_id,'command_name':comd,'command_value':value,'send_time':send_time,'command_style':command_style,'device_id':dev_id,
						 'command_result':'0','remark':'0','owner':owner}

			param_data={'device_id':dev_id,'param':param,'command_name':comd,'command_detail':command_detail}
			ip_port = ('localhost',port)
			sk = socket.socket()
			mesg_redis.lpush('car_set_param',str(param_data))
			sk_res=sk.connect_ex(ip_port)
			print('sk_res====>',sk_res)
			if sk_res!=0:
				result=sk_res
				res['code']=1234
				res['error']='连接错误'
			else:
				result = sk.recv(1024)
				result = result.decode()
				sk.close()
	else:
		result='command file not found!'
		res['code']=1234
		res['error']='找不到-'+device_model+'-的命令文件'

	print('result==>',res)
	return res


def get_lbs_address(lbs_data,device_id,only_from_db='no'):
	lbs_data=eval(lbs_data)
	all_lbs=[]
	for x in lbs_data:
		lbs=x['MCC']+','+x['MNC']+','+x['sid']+','+x['nid']+','+str(x['rssi'])
		all_lbs.append(lbs)
	bts_lbs=all_lbs[0]
	all_lbs='|'.join(all_lbs)
	lbs_lng='0'
	lbs_lat='0'
	zh_address='0'
	lbs_accuracy='0'
	mcc=lbs_data[0]['MCC']
	mnc=lbs_data[0]['MNC']
	lbs_nid=lbs_data[0]['nid']
	lbs_sid=lbs_data[0]['sid']
	lbs_mac=lbs_sid+lbs_nid
	lbs_address=WIFI_LBS_ADDR.objects.filter(mac=lbs_mac).first()
	# print('all_lbs=======>',all_lbs)
	if lbs_address==None and only_from_db=='no':

		# print(only_from_db)
		# get_lbs='http://api.cellocation.com:81/cell/?mcc='+mcc+'&mnc='+mnc+'&lac='+lbs_sid+'&ci='+lbs_nid+'&output=json'
		get_lbs='http://apilocate.amap.com/position?accesstype=0&imei='+device_id+'&cdma=0&bts='+bts_lbs+'&'+all_lbs+'&key=0ff8329afe2ab4e379f6af1f555c86b7'
		lbs_loca=requests.get(get_lbs)
		lbs_loca=eval(lbs_loca.text)
		if lbs_loca.get('info')=='OK' and lbs_loca.get('status')=='1':
			response_result=lbs_loca['result']
			if response_result.get('location')!=None:
				lnglat=response_result['location'].split(',')
				# 获取的是高德地图的的接口，得到的数据为gcj02的经纬度，此处转为原始的wgs84
				change_l=gcj02_to_wgs84(float(lnglat[0]),float(lnglat[1]))
				lbs_lng=change_l['lng']
				lbs_lat=change_l['lat']
				lbs_accuracy=response_result['radius']
				zh_address=response_result['desc']
				try:
					WIFI_LBS_ADDR.objects.create(mac=lbs_mac,ssid=str([mcc,mnc]),rssi=lbs_data[0]['rssi'],lng=lbs_lng,lat=lbs_lat,kind='lbs',
												location=str(response_result))
				except Exception as e:
					raise
	elif lbs_address!=None:

		lbs_lng=lbs_address.lng
		lbs_lat=lbs_address.lat
		zh_address=lbs_address.location

	return lbs_lng,lbs_lat,zh_address

def get_wifi_address(wifi_data,device_id,only_from_db='no'):
	# print(type(device_id))
	device_id=str(device_id)
	wifi_data=eval(wifi_data)
	all_mac=[]
	repeat_mac=[]
	# 去掉重复
	for x in wifi_data:
		if x['mac'] not in repeat_mac:
			mac=x['mac']+','+str(x['rssi'])
			all_mac.append(mac)
			repeat_mac.append(x['mac'])
	# 高德的wifi接口，必须2个wifi mac以上才有地址
	if len(all_mac)==1:
		all_mac='0'
	else:
		all_mac='|'.join(all_mac)
	f_wifi_mac=wifi_data[0]['mac']
	wifi_ssid=wifi_data[0]['ssid']
	wifi_rssi=wifi_data[0]['rssi']
	wifi_lng='0'
	wifi_lat='0'
	zh_address='0'
	wifi_accuracy='0'
	wifi_address=WIFI_LBS_ADDR.objects.filter(mac=f_wifi_mac).first()
	def get_address(save_kind):
		# print(only_from_db)
		get_url='http://apilocate.amap.com/position?accesstype=1&imei='+device_id+'&macs='+all_mac+'&key=0ff8329afe2ab4e379f6af1f555c86b7'
		# print(get_url)
		# print(wifi_data)
		wifi_loca=requests.get(get_url)
		wifi_loca=eval(wifi_loca.text)
		# print('wifi_loca====>',wifi_loca)
		if wifi_loca.get('info')=='OK' and wifi_loca.get('status')=='1':
			response_result=wifi_loca['result']
			if response_result.get('location')!=None:
				lnglat=response_result['location'].split(',')
				# 获取的是高德地图的wifi转lnglat的接口，得到的数据为gcj02的经纬度，此处转为原始的wgs84
				change_l=gcj02_to_wgs84(float(lnglat[0]),float(lnglat[1]))
				wifi_lng=change_l['lng']
				wifi_lat=change_l['lat']
				wifi_accuracy=response_result['radius']
				zh_address=response_result['desc']
				if save_kind=='save':
					WIFI_LBS_ADDR.objects.create(mac=f_wifi_mac,ssid=wifi_ssid,rssi=wifi_rssi,lng=wifi_lng,lat=wifi_lat,kind='wifi',
												location=str(response_result))
				elif save_kind=='update':
					WIFI_LBS_ADDR.objects.filter(mac=f_wifi_mac).update(ssid=wifi_ssid,sid='0',nid='0',mcc='0',mnc='0',rssi=wifi_rssi,lng=wifi_lng,lat=wifi_lat,kind='wifi',
																	location=str(response_result),date_added=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
					# session.update(WIFI_LBS_ADDR(mac=f_wifi_mac,))
				session.commit()
			else:
				if save_kind=='save':
					WIFI_LBS_ADDR.objects.create(mac=f_wifi_mac,ssid=wifi_ssid,sid='0',nid='0',mcc='0',mnc='0',rssi=wifi_rssi,lng='0',lat='0',kind='wifi',
													location=str(wifi_data),date_added=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
					session.commit()

	# wifi地址没有存库的情况下，通过接口获取的数据，分为有经纬度和无经纬度两种，有经纬度的在location存储具体的返回信息，没有经纬度的存储原来的wifi数据
	if wifi_address==None and only_from_db=='no' and all_mac!='0' :
		get_address('save')
		
	# wifi地址有存库，但是存储的经纬度为零，并且新请求的wifi数据与原先存储的wifi数据不一样的是，可以再次进行wifi转地址的接口请求
	elif wifi_address!=None :
		if str(wifi_data)!=wifi_address.location and wifi_address.lng=='0':
			get_address('update')
		else:
			wifi_lng=wifi_address.lng
			wifi_lat=wifi_address.lat
			zh_address=wifi_address.location
	# print(wifi_lng,wifi_lat,zh_address)
	return wifi_lng,wifi_lat,zh_address



	
# 设备运行统计-在线时长
def device_statistic(device_id,s_time,e_time):
	res={'online':0,'offline':0,'active_time':0,'stop_time':0,'speed':0,'mileage':0,'query_time':0}
	data=pd.read_sql_query('select * from "'+device_id+'" where serv_receive between \''+s_time+'\' and \''+e_time+'\'',engine)
	if data.shape[0]>2:
		# 按照时间排序，重置index索引
		data=data.sort_values('serv_receive')
		data=data.reset_index(drop=True)
		# 把设备上传的时间，转换为时间戳，即，秒
		data.loc[:,'timestamp'] = data['serv_receive'].apply(lambda x:time.mktime(time.strptime(x,'%Y-%m-%d %H:%M:%S')))
		query_time=data['timestamp'].iloc[-1]-data['timestamp'].iloc[0]
		res['query_time']=round(int(query_time)/3600,1)
		
		# 计算两点之间的时间差，秒，大于600秒的视为离线，即后一行减去前一行，从顺序来说，第2-第1
		data.loc[:,'serv_receive_sub']=data['timestamp']-data['timestamp'].shift(1)
		data=data.fillna(0)
		data.loc[:,'online']=data['serv_receive_sub'].map(lambda x:x if x<1800 else 0)
		online=data.loc[data['online']!=0].copy()
		if online.shape[0]>0:
			online_time=online['online'].sum()
			res['online']=round(int(online_time)/3600,1)
			res['online_xAxis']=online['serv_receive'].tolist()
			res['online_yAxis']=online['online'].tolist()

		offline=data.loc[data['online']==0].copy()
		if offline.shape[0]>0:
			offline_time=offline['serv_receive_sub'].sum()
			res['offline']=round(int(offline_time)/3600,1)
			res['offline_xAxis']=offline['serv_receive'].tolist()
			res['offline_yAxis']=offline['serv_receive_sub'].tolist()

		data['speed'] = pd.to_numeric(data['speed'])
		speed=data.loc[data['speed']!=0].copy()
		
		if speed.shape[0]>0:
			speed_aver=speed['speed'].mean()
			res['speed']=round(float(speed_aver),1)
			res['speed_xAxis']=speed['serv_receive'].tolist()
			res['speed_yAxis']=speed['speed'].tolist()
			active_time=speed['serv_receive_sub'].sum()
			res['active_time']=round(int(active_time)/3600,1)
			res['active_xAxis']=speed['serv_receive'].tolist()
			res['active_yAxis']=speed['serv_receive_sub'].tolist()
			# res['stop_time']=round((int(online)-int(active_time))/3600,1)

		stop=data.loc[data['speed']==0].copy()
		if stop.shape[0]>0:
			stop_time=stop['serv_receive_sub'].sum()
			res['stop_time']=round(int(stop_time)/3600,1)
			res['stop_xAxis']=stop['serv_receive'].tolist()
			res['stop_yAxis']=stop['serv_receive_sub'].tolist()

		# data.loc[:,'speed_sub']=data['speed']-data['speed'].shift(1)
		# active=data.loc[data['speed_sub']!=data['speed']].copy()
		mileage=data.loc[data['mileage']!='0'].copy()
		if mileage.shape[0]>1:
			mileage['mileage'] = pd.to_numeric(mileage['mileage'])
			total_mileage=mileage['mileage'].iloc[-1]-mileage['mileage'].iloc[0]
			res['mileage']=round(float(total_mileage),1)
			res['mileage_xAxis']=mileage['serv_receive'].tolist()
			res['mileage_yAxis']=mileage['mileage'].tolist()

	return res

def alarm_statistic(device_id,s_time,e_time):
	res={'alarm_kind':{},'alarm_time':{},'alarm_location':{},'alarm_detail':[]}
	data=pd.read_sql_query('select * from car_app_alarm where device_id=\''+device_id+'\' and s_time between \''+s_time+'\' and \''+e_time+'\'',engine)
	if data.shape[0]>1:
		# 报警类型
		alarm_detail=json.loads(data.to_json(orient="records",force_ascii=False))
		res['alarm_detail']=alarm_detail
		data=data.sort_values('s_time')
		data=data.reset_index(drop=True)
		alarm_kind=data.groupby('kind')['kind'].count().to_dict()
		res['alarm_kind']=alarm_kind
		# 时段获取
		data.loc[:,'alarm_time']=data['s_time'].map(lambda x:x[11:13])
		alarm_time=data.groupby('alarm_time')['alarm_time'].count().to_dict()
		res['alarm_time']=alarm_time
		# 地点
		def handle_alarm_location(loca,device_id):
			# print('loca==>',loca)
			try:
				loca=eval(loca)
			except:
				loca={}
			ala_loca=['0','0']

			if isinstance(loca,dict)==True:
				if loca.get('satelite')!=None:
					ala_loca=loca.get('satelite')
				elif loca.get('wifi')!=None:
					ala_loca=get_wifi_address(loca.get('wifi'),device_id)
				elif loca.get('lbs')!=None:
					ala_loca=get_wifi_address(loca.get('lbs'),device_id)

			# print('ala_loca===========>',ala_loca)
			alarm_lng=ala_loca[0]
			alarm_lat=ala_loca[1]
			alarm_lng=round(float(alarm_lng),5)
			alarm_lat=round(float(alarm_lat),5)
			return str([alarm_lng,alarm_lat])

		data.loc[:,'alarm_location']=data.apply(lambda x:handle_alarm_location(x['location'],x['device_id']),axis=1)
		alarm_location=data.groupby('alarm_location')['alarm_location'].count().to_dict()
		res['alarm_location']=alarm_location
	# print({'alarm_kind':alarm_kind,'alarm_time':alarm_time,'alarm_location':alarm_location})
	return res